实现Comparable接口的自然排序 实现类基于compareTo()方法的排序被称为自然排序,在JDK中,如Integer,Double和String等都实现了Comparable接口的,接口中有一个int compartTo(Object o)方法,返回整数类型.
Comparator接口的自定义排序 实现Comparator接口的类会实现一个compare(Object o1, Object o2)的方法,如果类的设计没有考虑到Compare的问题而没有实现Comparable接口,可以通过Comparator 来实现比较算法进行排序,而且可以自定义升序还是降序
为Boy类实现Comparable接口,依据年龄排序
package com.perficient.basic;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Boy implements Comparable{
private String name;
private int age;
public Boy(String name, int age) {
this.name = name;
this.age = age;
}
//Getters and Setters......
//依据年龄来排序
public int compareTo(Object o) {
int result = 0;
Boy other = (Boy)o;
if (this.age > other.age) result = 1;
if (this.age < other.age) result = -1;
return result;
}
TreeSet能对集合采用自然排序,使用它去测试
public static void main(String[] args){
Set<Boy> boys = new TreeSet<Boy>();
Boy boy1 = new Boy("James", 28);
Boy boy2 = new Boy("Hank", 40);
Boy boy3 = new Boy("Billy", 15);
boys.add(boy1);
boys.add(boy2);
boys.add(boy3);
Iterator<Boy> it = boys.iterator();
while (it.hasNext()){
Boy boy = (Boy) it.next();
System.out.println(boy.getName()+" age:" + boy.getAge());
}
查看运行结果:
Billy age:15
James age:28
Hank age:40
创建Boy类的Comparator
package com.perficient.basic;
import java.util.Comparator;
public class BoyComparator implements Comparator<Boy>{
//依据年龄进行比较
public int compare(Boy boy1, Boy boy2) {
int result = 0;
if (boy1.getAge()> boy2.getAge()) result =1;
if (boy1.getAge()< boy2.getAge()) result =-1;
return result;
}
}
使用Arrays.sort()方法去测试BoyComparator类:
public static void main(String[] args){
Boy boy1 = new Boy("James", 28);
Boy boy2 = new Boy("Hank", 40);
Boy boy3 = new Boy("Billy", 15);
Boy[] boys2 = {boy1, boy2, boy3};
Arrays.sort(boys2, new BoyComparator());
System.out.println(Arrays.toString(boys2));
}
运行结果
[Billy: 15, James: 28, Hank: 40]