java里的Collections类中的静态方法sort()是怎么用比较器比较两个对象?

来源:百度知道 编辑:UC知道 时间:2024/05/22 16:42:03
我写了个类:
class Light{
String name;
float price;
Date date;

public Light(String name,float price,Date date){
this.name=name;
this.price=price;
this.date=date;
}

public String toString(){
return "name:"+this.name+" price:"+this.price;
}

public void setDate(Date date){
this.date=date;
}

public Date getDate(){
return this.date;
}
}
现在比较两个Light对象怎么比较,我知道要实现Comparator接口,但具体就不知道了。

1、定义一个实现Comparator接口的类如:LightComparator,然后实现public int compare(Object o1,Object o2)方法。这个方法的实现将决定你是以何种方式排序。例如:你根据价格排序,那么这个方法实现为:

public int compare(Object o1,Object o2){
Light l1 = (Light)o1;
Light l2 = (Light)o2;

return (int)(l1.getPrice()-l2.getPrice());
}//假定你这个类里有get set方法。

2、运用Collections排序,提供一个List(保存的是Light对象)设为list:
Collections.sort(list,new LightComparator());

sort
public static <T> void sort(List<T> list,
Comparator<? super T> c)根据指定比较器产生的顺序对指定列表进行排序。此列表内的所有元素都必须可使用指定比较器相互比较(也就是说,对于列表中的任意 e1 和 e2 元素,c.compare(e1, e2) 不得抛出 ClassCastException)。
此排序被保证是稳定的:不会因调用 sort 而对相等的元素进行重新排序。

排序算法是一个经过修改的合并排序算法(其中,如果低子列表中的最高元素小于高子列表中的最低元素,则忽略合并)。此算法提供可保证的 n log(n) 性能。 指定列表必须是可修改的,但不必是可大小调整的。此实现将指定列表转储到一个数组中,并对数组进行排序,在重置数组中相应位置每个元素的列表上进行迭代。这避免了由于试图原地对链接列表进行排序而产生的 n2 log(n) 性能。

参数:
list - 要排序的列表。
c - 确定列表顺序的比较器。null 值指示应该使用元素的自然顺序。