TreeSet与TreeMap 实现comparable接口以及compare()的重写

更多内容请关注我的个人博客:

comparable方法的重写,我们以TreeMap为例:

方法一(让引用数据类型student继承comparable接口):

public class Student implements Comparable {
    private String name;
    private int age;
    public Student() {
        super();
        
    }
    public Student(String name, int age) {
        super();
        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 "Student [name=" + name + ", age=" + age + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    @Override
    public int compareTo(Student o) {
        int num = this.age - o.age;                 //以年龄为主要条件
        return num == 0 ? this.name.compareTo(o.name) : num;
    }
}

方法二(重写方法):

public class TreeSetDemo {
    public static void main(String[] args) {
        TreeSet pset=new TreeSet(new Comparator() {

    @Override
// 匿名内部类来实现按照年龄的升序进行排序,并去重(记住还要去到person类中重写equals()和HashCode()方法)
    public int compare(Person2 p1, Person2 p2) {
        int num = p1.getAge - p2.getAge;
                return num == 0? p1.getName.compareTo(p2.getName) : num;
            }
        });

pset.add(new Person(23,"shehshe"));

如果只是想排序,不去重

public int compare(Person2 p1, Person2 p2) {
        int num = p1.getAge - p2.getAge;
                return num == 0? 1 : num;
            }
        });

倒序就是p2.getAge - p1.getAge;

你可能感兴趣的:(TreeSet与TreeMap 实现comparable接口以及compare()的重写)