普通情况下在实现对对象元素的数组或集合进行排序的时候会用到Comparator和Comparable接口,通过在元素所在的类中实现这两个接口中的一个。然后对数组或集合调用Arrays.sort或者Collentions.sort方法就可以实现对数组或集合的排序。就sort方法里面的參数来说。实现了不同的接口则传递的參数也不尽同样。对于实现了Comparator接口的类来说。sort方法须要接受的參数不仅包含数组或集合。还要包含实现了该接口的类对象。而对实现了Comparable接口的类来说,參数不仅包含数组或者集合,还要包含实现了该接口的类对象。

详细怎么差别呢,事实上非常easy,由于看两个接口所实现的方法就知道,Comparator定义的方法为compare(Object o1, Object o2)。方法涉及两个类对象。所以须要在另外一个新的类来实现对数组元素的比較,所以在调用sort方法时须要传递这个额外的实现了Comparator接口的类对象;而实现了Comparable接口的类实在元素类的内部实现了排序的逻辑,所以调用sort方法时不须要传递额外的类对象。废话少说,直接上代码。

1.通过实现Comparator接口来实现对数组或集合的比較

class SortCat implements Comparator<Cat1>
{
@Override
public int compare(Cat1 o1, Cat1 o2)//实现了Comparator接口的compare方法
{
// TODO Auto-generated method stub
int size1=o1.getSize(),size2=o2.getSize();
if(size1!=size2)
return size1-size2;
return o1.getColor().compareTo(o2.getColor());
}
}
class Cat1
{
private String color;
private int size;
public Cat1(String color,int size)
{
this.color=color;
this.size=size;
}
public int getSize()
{
return size;
}
public String getColor()
{
return color;
}
public String toString()
{
return color+" cat,size = "+size;
} }
public class HashMapComparatorDemo
{ public static void main(String[] args)
{
// TODO Auto-generated method stub
String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
int catSizeArr[]={5,3,7,9,6,4,1,8,2};
Random random=new Random();
Cat1 catArr[]=new Cat1[10];
int sizeIndex=0,colorIndex=0;
for(int i=0;i<10;i++)
{
sizeIndex=random.nextInt(catSizeArr.length);
colorIndex=random.nextInt(colorArr.length);
catArr[i]=new Cat1(colorArr[colorIndex], catSizeArr[sizeIndex]);
System.out.println("Color:"+catArr[i].getColor()+",size:"+catArr[i].getSize());
}
System.out.println("\nAfter change the order....\n");
Arrays.sort(catArr,new SortCat());//不仅要传递数组參数。还要传递实现了Comparator接口的类对象
for(Cat1 cat:catArr)
System.out.println("Color:"+cat.getColor()+",size:"+cat.getSize()); } }

结果:

Color:white,size:4
Color:colorful,size:4
Color:colorful,size:4
Color:gray,size:5
Color:yellow,size:7
Color:orange,size:6
Color:black,size:2
Color:colorful,size:8
Color:black,size:3
Color:yellow,size:2 After change the order.... Color:black,size:2
Color:yellow,size:2
Color:black,size:3
Color:colorful,size:4
Color:colorful,size:4
Color:white,size:4
Color:gray,size:5
Color:orange,size:6
Color:yellow,size:7
Color:colorful,size:8

2.通过实现Comparable接口来实现对数组或集合的比較

class Cat2  implements Comparable<Cat2>
{
private String color;
private int size;
public Cat2(String color,int size)
{
this.color=color;
this.size=size;
}
public int getSize()
{
return size;
}
public String getColor()
{
return color;
}
public String toString()
{
return color+" cat,size = "+size;
}
@Override
public int compareTo(Cat2 o)//在元素类里面实现comparable接口所定义的方法
{
// TODO Auto-generated method stub
int size=o.getSize();
if(this.size!=size)
return this.size-size;
return this.color.compareTo(o.getColor());
} }
public class HashMapComparatorDemo2
{ public static void main(String[] args)
{
String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
int catSizeArr[]={5,3,7,9,6,4,1,8,2};
Random random=new Random();
Cat2 catArr[]=new Cat2[10];
int sizeIndex=0,colorIndex=0;
for(int i=0;i<10;i++)
{
sizeIndex=random.nextInt(catSizeArr.length);
colorIndex=random.nextInt(colorArr.length);
catArr[i]=new Cat2(colorArr[colorIndex], catSizeArr[sizeIndex]);
System.out.println("Color:"+catArr[i].getColor()+",size:"+catArr[i].getSize());
}
System.out.println("\nAfter change the order....\n");
Arrays.sort(catArr);//仅须要传递数组或集合就可以
for(Cat2 cat:catArr)
System.out.println("Color:"+cat.getColor()+",size:"+cat.getSize()); } }

结果:

Color:gray,size:7
Color:orange,size:9
Color:gray,size:3
Color:brown,size:5
Color:orange,size:1
Color:gray,size:8
Color:colorful,size:9
Color:white,size:1
Color:blue,size:7
Color:brown,size:1 After change the order.... Color:brown,size:1
Color:orange,size:1
Color:white,size:1
Color:gray,size:3
Color:brown,size:5
Color:blue,size:7
Color:gray,size:7
Color:gray,size:8
Color:colorful,size:9
Color:orange,size:9

3.另外。还能够用实现了对Comparable接口treeMap、treeSet进行排序,详细应用范围非常广。包含求一个无反复无序数组的前k项元素就能够用treeSet或treeMap非常好滴实现,循环建tree并维持一个大小为k的treeSet或treeMap就可以。超出范围的话先插入一个元素。然后删除排在最后的元素就可以。以下这段代码只实现的是有序建树并将treeMap输出出来的功能。

class Cat implements Comparable<Cat>
{
private String color;
private int size;
public Cat(String color,int size)
{
this.color=color;
this.size=size;
}
public int getSize()
{
return size;
}
public String getColor()
{
return color;
}
@Override
public int compareTo(Cat o)
{
// //优先依据颜色排序
// String color1=o.getColor();
// if(this.color.compareTo(color1)!=0)
// return this.color.compareTo(color1);
// return this.size-o.size;
//优先依据大小排序
int size=o.getSize();
if(this.size!=size)
return this.size-size;
return this.color.compareTo(o.getColor());
}
public String toString()
{
return "Color:"+color+",size = "+size;
}
}
public class HashMapComparableDemo
{ public static void main(String[] args)
{
SortedMap<Cat, Integer>map=new TreeMap();
String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
int catSizeArr[]={5,3,7,9,6,4,1,8,2};
Random random=new Random();
int sizeIndex=0,colorIndex=0,count=0;;
int mapSize=10;
for(int i=0;i<mapSize;i++)
{
sizeIndex=random.nextInt(catSizeArr.length);
colorIndex=random.nextInt(colorArr.length);
count=random.nextInt(20)+5;
map.put(new Cat(colorArr[colorIndex], catSizeArr[sizeIndex]), count);
}
Iterator<Entry<Cat, Integer>>iterator=map.entrySet().iterator();
Entry<Cat, Integer>entry;
while(iterator.hasNext())
{
entry=iterator.next();
System.out.println(entry.getKey().toString()+",Count:"+entry.getValue().toString());
} } }

结果:

Color:black,size = 1,Count:15
Color:black,size = 2,Count:12
Color:gray,size = 2,Count:24
Color:brown,size = 5,Count:24
Color:gray,size = 5,Count:14
Color:brown,size = 6,Count:13
Color:white,size = 6,Count:7
Color:yellow,size = 6,Count:12
Color:gray,size = 7,Count:9
Color:brown,size = 8,Count:17

另外:对某些对象建立treeMap或hashMap的时候还须要重写一下equals方法,防止发生插入同样元素的情况,由于默认情况下treeMap或HashMap是应该是以对象的引用作为各个对象元素的标志。而不是元素的值。

Java中Comparator接口和Comparable接口的使用的更多相关文章

  1. java中的类实现comparable接口 用于排序

    import java.util.Arrays; public class SortApp { public static void main(String[] args) { Student[] s ...

  2. Java中 Comparator接口 与Comparable 的区别

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt159 comparator接口与Comparable接口的区别 1. Com ...

  3. 在java中,List是个接口,那实现List接口的类有哪些,有什么区别?

    在java中,List是个接口,那实现List接口的类有哪些,有什么区别? 解答: ArrayList是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引 ...

  4. 如何理解 Java 中的 <T extends Comparable<? super T>>

    Java 中类似 <T extends Comparable<? super T>> 这样的类型参数 (Type Parameter) 在 JDK 中或工具类方法中经常能看到. ...

  5. Java Comparator方法 和 Comparable接口

    默认的排序方法: 让类继承Comparable接口,重写compareTo方法. 示例代码: package com.imooc.collection; import java.util.HashSe ...

  6. Java 之 比较器( Comparator接口与 Comparable 接口)

    一.定制排序:java.util.Comparator 接口 强行对某个对象 collection 进行整体排序 的比较函数.可以将 Comparator 传递给 sort 方法(如 Collecti ...

  7. Java中的TreeMap、Comparable、Comparator

    我们知道HashMap的存储位置是按照key这个对象的hashCode来存放的,而TreeMap则是不是按照hashCode来存放,他是按照实现的Comparable接口的compareTo这个方法来 ...

  8. 关于comparator接口和comparable接口以及它们各自的方法compare()和compareTo()

    在今天做的LeetCode的题中有两道都出现了利用接口实现对象的排序.两题的相关链接: 1.利用comparable接口对对象排序 2.利用comparator接口实现排序 因为之前都没接触过这两个接 ...

  9. 实现Comparator接口和Comparable接口,以及Map按value排序 ,map遍历

    继承Comparator接口,重写compare()方法 import java.util.ArrayList; import java.util.Arrays; import java.util.C ...

随机推荐

  1. 【Gambit】Gambit使用教程

    第一章 Gambit使用 Gambit介绍 网格的划分使用Gambit软件,首先要启动Gambit,在Dos下输入Gambit <filemane>,文件名如果已经存在,要加上参数-old ...

  2. 迅为i.MX6UL核心板ARMCortex-A7单核NXP飞思卡尔工控行业Imx6核心板

    iMX6UL核心板小巧精致,尺寸仅38mm*42mm:CPU型号iMX6UL@ 528MHz ARM Cortex-A7架构 :内存:512M DDR :存储:8G EMMC,低功耗,性能强大,性价比 ...

  3. Android(java)学习笔记194:ContentProvider使用之获得系统联系人信息02(掌握)

    1.重要: 系统删除一个联系人,默认情况下并不是把这个联系人直接删除掉了,只是做了一个标记,标记为被删除. 2.前面一讲说过了如何获取系统联系人信息(通过ContentProvider),获取联系人信 ...

  4. 使用JDBC创建出版社和书籍管理系统

    1.需求 已知如下两个表: publisher id name(唯一) address book id isbn name publisher_id 欢迎进入书籍管理系统 1.出版社管理:增.删(na ...

  5. Laravel 的 API 认证系统 Passport 三部曲(二、passport的具体使用)

    GQ1994 关注 2018.04.20 09:31 字数 1152 阅读 1316评论 0喜欢 1 参考链接 Laravel 的 API 认证系统 Passport 三部曲(一.passport安装 ...

  6. console.log()与console.dir()

    console.log()可以取代alert()或document.write(),在网页脚本中使用console.log()时,会在浏览器控制台打印出信息. console.dir()可以显示一个对 ...

  7. [0] Hello World

    受不了CSDN了,广告多,慢,编辑器难用,还限制博客数量.

  8. <Linux> 下安装和卸载JDK

    安装 下载jdk https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 在local ...

  9. Ajax实现跨域访问最新方式

    在实际项目当中,我们经常会遇到同一个域名下不同项目之间通过Ajax相互调用数据,这样问题就来了,如何通过Ajax实现跨域呢? 解决方案 1.Jsonp Jsonp解决跨域相对简单,服务器无需任何配置. ...

  10. Anaconda基本用法

    Anaconda基本用法 conda info --envs/(-e) // 查看当前的环境变量 conda create -n py36(环境的名称,随意) python=3.6(指定版本) //  ...