集合排序类Comparable和Comparator区别小结
Comparable简介
Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。注意:Comparable须实现compareTo方法。
测试代码:
public static void main(String[] args) {
// 自定义类
Map m2 = new TreeMap();
m2.put(new Person(12),"name");
m2.put(new Person(28),"name");
m2.put(new Person(333),"name");
m2.put(new Person(999),"name");
Set s = m2.keySet();
Iterator i2 = s.iterator();
while (i2.hasNext()) {
Object k = i2.next();
Object v = m2.get(k);
System.out.println(k+"---->"+v);
}
}
class Person2 implements Comparable {
// 实现compareTo方法
@Override
public int compareTo(Object o) {
int o1 = this.age;
int o2 = ((Person2)o).getAge();
if (o1==02) {
return 0;
}else if (o1>o2) {
return 1;
}else {
return -1;
}
}
private int age;
public Person2(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person2{" +
"age=" + age +
'}';
}
}
Comparator简介
Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过实现Comparator来新建一个比较器,然后通过这个比较器对类进行排序。注意:Comparator须实现compare方法。
测试代码:
public static void main(String[] args) {
Map m2 = new TreeMap(new Person2Sort());
m2.put(new Person2(12),"name");
m2.put(new Person2(28),"name");
m2.put(new Person2(333),"name");
m2.put(new Person2(999),"name");
Set s = m2.keySet();
Iterator i2 = s.iterator();
while (i2.hasNext()) {
Object k = i2.next();
Object v = m2.get(k);
System.out.println(k+"---->"+v);
}
}
class Person2 {
private int age;
public Person2(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person2{" +
"age=" + age +
'}';
}
}
class Person2Sort implements Comparator {
public int compare(Object o1,Object o2) {
int age1 = ((Person2)o1).getAge();
int age2 = ((Person2)o2).getAge();
if (age1==age2) {
return 0;
}else if (age1 > age2) {
return 1;
}else {
return -1;
}
}
}