38.TreeSet Teacher排序

package com.itheima.myTreeSet;

public class Teacher {
    private String name;
    private int age;

    public Teacher() {
    }

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.itheima.myTreeSet;

import java.util.Comparator;
import java.util.TreeSet;

public class MyTreeSet4 {
    public static void main(String[] args) {
        TreeSet treeSet=new TreeSet<>(new Comparator() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                int  result=o1.getAge()-o2.getAge();
                result=(result==0?o1.getName().compareTo(o2.getName()):result);
                return result;
            }
        });
        Teacher t1=new Teacher("zhansan",23);
        Teacher t2=new Teacher("lisi",22);
        Teacher t3=new Teacher("wangwu",24);
        Teacher t4=new Teacher("zhaoliu",24);
        treeSet.add(t1);
        treeSet.add(t2);
        treeSet.add(t3);
        treeSet.add(t4);
        System.out.println(treeSet);
    }
}

你可能感兴趣的:(JAVAWeb,java,开发语言,后端)