参考http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html
Java容器类不能存放基本类型,比如int。
List可以通过Collections.sort的方式进行排序
若List中存储的元素已经实现comparable类型,则直接调用Collections.sort方法即可,否则需实现Comparable接口。
或者调用Collections.sort的两个参数版本的函数,第2个参数传递一个Comparator对象即可
Comparable接口由下面的方法组成
public interface Comparable<T> { public int compareTo(T o); }
Comparator
如果想排序没有实现Comparable接口的对象,或者不按照自然顺序排序,这时便需要提供一个Comparator
Comparator接口只包含一个方法
public interface Comparator<T> { int compare(T o1, T o2); }
The compare
method compares its two arguments, returning a negative integer, 0, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second. If either of the arguments has an inappropriate type for the Comparator
, the compare
method throws a ClassCastException
其中介绍了Comparator的方法中为了比较两个数的大小使用了
return e1.number() - e2.number();
跟我之前实现的一样。这种是有潜在的bug的,oracle的tutorial中介绍因为可能前一个数是个很大的正数,后一个数是很小的复数,两数之差可能导致溢出
下例是用Collections.sort方法对容器中的对象进行排序的例子。
需实现Comparator类及Comparator类中的sort方法
import java.util.*;
class Car {
public Car(int m) {
this.price = m;
}
public int getPrice() {
return this.price;
}
private int price;
};
public class Test {
public static void main(String[] args) {
// List is a interface
List<Car> l = new ArrayList<Car>();
l.add(new Car(5));
l.add(new Car(9));
l.add(new Car(8));
l.add(new Car(7));
for (Car i : l) {
System.out.println(i.getPrice());
}
Collections.sort(l, new Comparator<Car>() {
// a negative integer, zero, or a positive integer as this object
// is less than, equal to, or greater than the specified object
@Override
public int compare(Car arg0, Car arg1) {
// TODO Auto-generated method stub
// potential risk,maybe overflow
// return arg0.getPrice()-arg1.getPrice()
return (arg0.getPrice() < arg1.getPrice() ? -1 : (arg0
.getPrice() == arg1.getPrice() ? 0 : 1));
}
});
Iterator<Car> iter = l.iterator();
while (iter.hasNext()) {
Car c = iter.next();
System.out.println(c.getPrice());
}
}
}