一.前言
java中对泛型(集合类型)排序的问题,主要采用了两张方式一种是对要排序的实体类,实现Comparable接口,另一种方式,Collections集合工具类进行排序。
二.实现Comparable接口方式
package com.shine.demo.test; import java.io.Serializable; public class Car implements Serializable, Comparable<Car> { /**
* 序列化版本.
*/
private static final long serialVersionUID = 5854674665110917200L; private Long id; private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public int compareTo(Car car) {
if(!this.id.equals(car.getId()))
return this.id.compareTo(car.getId());
else if(!this.name.equals(car.getName()))
return this.name.compareTo(car.getName()); return 0;
} @Override
public String toString() {
return "Car的id为:" + this.id + ",名称为:" + this.name;
} }
实现了Comparable接口,重写compareTo方法。
三.Collections集合工具
package com.shine.demo.test; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet; public class Test { public static void main(String[] args) { Car car = new Car();
car.setId(1L);
car.setName("小汽车"); Car car1 = new Car();
car1.setId(2L);
car1.setName("货车"); Car car2 = new Car();
car2.setId(3L);
car2.setName("载客小汽车"); Car car3 = new Car();
car3.setId(4L);
car3.setName("出租车"); //使用Comparable与Set进行排序
Set<Car> cars = new TreeSet<Car>();
cars.add(car);
cars.add(car3);
cars.add(car1);
cars.add(car2); for (Car carInfo : cars) {
System.out.println(carInfo);
} //常用Collections的sort排序
List<Car> carList = new ArrayList<Car>();
carList.add(car);
carList.add(car3);
carList.add(car1);
carList.add(car2); Collections.sort(carList, new Comparator<Car>() { @Override
public int compare(Car car1, Car car2) {
return (int) (car1.getId() - car2.getId());
}
}); for (Car carInfoList : carList) {
System.out.println(carInfoList);
} } }
采用了Collections的sort排序方法,其原理是利用了Comparator的类,进行排序。
结果: