java中TreeSet的Comparator比较器的三种使用方法

java中treeset使用Comparator进行比较的三种方法

1.让元素具备比较性。
比如我们比较两个人。我们定义一个person类,并且实现Comparable接口
例:
public class Person implements Comparable{
private int age;
private String name;

public Person(){}

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

public int getAge() {
    return age;
}

public String getName() {
    return name;
}

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

@Override
public int compareTo(Object o) {
    if (!(o instanceof Person))
        throw new RuntimeException("不是人对象");
    Person p = (Person) o;
    if (this.age > p.age)
        return 1;
    if (this.age == p.age){
        return this.name.compareTo(p.name);
    }
    return -1;
}

}

2.第二种是写个类实现Comparator接口
例:

     class myComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;

        int num = p1.getName().compareTo(p2.getName());
      // 0的话是两个相同,进行下一个属性比较
        if (num == 0){
            return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
        }

        return num;
    }
}

然后在new Set的时候放进去。如
TreeSet ts = new TreeSet(new myComparator());

3.第三种写内名内部类方法如:

    TreeSet ts = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            Person p1 = (Person) o1;
            Person p2 = (Person) o2;

            int num = p1.getName().compareTo(p2.getName());

            if (num == 0){
                return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
            }

            return num;

        }
    });

你可能感兴趣的:(java)