TreeMap代码演示;如何使用Comparator自定义构造器接口
@Data
public class Test{
private String name;
private Integer age;
private String sex;
public Test(){}
public Test(String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
}
class Demo{
public static void main(String[] args) {
Comparator<Test> comparator = new Demo10();
TreeMap<Test,Integer> treeMap = new TreeMap<>(comparator);
Test test1 = new Test("小哈",5,"男");
Test test2 = new Test("小金",4,"男");
Test test3 = new Test("小花",8,"女");
treeMap.put(test1,1);
treeMap.put(test2,2);
treeMap.put(test3,3);
System.out.println(treeMap);
TreeSet<Test> treeSet = new TreeSet(new Demo10());
treeSet.add(test1);
treeSet.add(test2);
treeSet.add(test3);
}
}
class Demo10 implements Comparator<Test>{
@Override
public int compare(Test o1, Test o2) {
return o1.getAge() - o2.getAge();
}
}