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;

        }
    });
  • 24
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值