Collections.sort(cars);
for(Car car : cars){
car.run();
}
}
}
==========================================================================
Comparator接口提供比较的方式,可以在运行时指定排序方式
Collections.sort(List集合,Comparator比较器)
interface Comparator{
int compare(T o1, T o2);
}
按多种方式进行排序
public static void main(String[] args) {
List cars = Arrays.asList(
new Car(“宝马X6”,1000000,5,2.0),
new Car(“奔驰S600”,1500000,6,3.0),
new Car(“奥迪A6”,400000,3,2.5),
new Car(“别克”,150000,8,1.8),
new Car(“丰田”,140000,2,1.0));
Scanner input = new Scanner(System.in);
System.out.println("请输入排序方式:1、价格 2、年限 3、排量 ");
int type = input.nextInt();
switch(type){
case 1:
//用匿名内部类实现Comparator,按价格排序
Colle