定义测试model类:
public class User {
private Integer age;
public User(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
测试类:
此处使用最简单的匿名内部类实现重写比较函数,虚拟参数为o1,o2,返回值为 o1-o2(也可以返回 JDk默认的比较参数 -1,0,1用来比较大小),这样就实现了升序排序。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Comparator_test {
public static void main(String[] args) {
List<User> integerList = new ArrayList<User>() {
{
add(new User(1));
add(new User(5));
add(new User(3));
}};
Collections.sort(integerList, new Comparator<User>() {
@Override
public int compare(U