TreeSet(对象排序功能)和自定义比较器

来源:互联网 发布:软件系统设计模板 编辑:程序博客网 时间:2024/06/05 02:53

排序功能:

package com.mth.test;class Person implements Comparable<Person> {    // 实现Comparable接口的目的,在于建立Person对象的自然顺序    public int compareTo(Person p) {// 方法中就是Person的自然顺序// 对类中的成员变量,进行自然顺序比较// this 小 结果是负数 两个一样 是0 this 大就是正数int num = this.name.compareTo(p.name);return num == 0 ? this.age - p.age : num;    }    private String name;    private int age;    Person(String name, int age) {this.name = name;this.age = age;    }    public String getName() {return name;    }    public int getAge() {return age;    }    public String toString() {return this.name + "..." + this.age;    }    public int hashCode() {// 覆盖的依据,就是对象中的成员变量 name age// 姓名 和年龄一样的对象,具有同样的hashCode// lisi 22 100 + 22*2 = 144(122)// wangwu 25 97 + 25*2 = 147(122)// 乘以2降低,姓名年龄不一致,恰巧计算出了相同的哈希值的问题 //如果对象的哈希值一样,Set集合比较equalsfinal int X = 2;return this.name.hashCode() + this.age * X;    }    public boolean equals(Object obj) {if (obj == null) {    return false;}if (this == obj)    return true;if (obj instanceof Person) {    Person p = (Person) obj;    return this.name.equals(p.name) && this.age == p.age;}return false;    }}


自定义比较器:

package com.mth.test;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;/* * 自定义自己的比较器 让TreeSet进行比较 * * *///第一步public class MyComparator implements Comparator<Person> {    // 自定义以年龄进行比较    @Override    public int compare(Person p1, Person p2) {// TODO Auto-generated method stubint num = p1.getAge() - p2.getAge();// 等于0?就判断名字 如果不等于的话 直接返回numreturn num == 0 ? p1.getName().compareTo(p2.getName()) : num;    }    // 第二步    // 只需要再new TreeSet对象的时候 把new MyComparator() 传进构造函数即可    Set<Person> pset = new TreeSet<Person>(new MyComparator());}



0 0
原创粉丝点击