对于TreeSet如果元素是对象,可以采用比较器的方式,来指定排序规则。 平衡二叉树的遍历方式默认是中序遍历,所以排序结果是从小到大输出。
1.使用自然排序 :实现Comparable接口,重写Compareto方法
public class User implements Comparable<User>{ private Integer id; private Integer age; public int compareTo(User o) { if(this.age > o.getAge()) { return 1; }else if(this.age < o.getAge()) { return -1; }else{ return 0; } } }2.指定比较器 创建一个比较类,实现Comparator接口,并重写compare(T o1, T o2)方法:
class StudentComparator implements Comparator<Student>{ // 实现比较器 // 因为Object类中本身已经有了equals()方法 public int compare(Student s1,Student s2){ if(s1.equals(s2)){ return 0 ; }else if(s1.getAge()<s2.getAge()){ // 按年龄比较 return 1 ; }else{ return -1 ; } } };指定比较器
Set<Student>treeSet =new TreeSet<Student>(new StudentComparator()); 溪源的奇思妙想 认证博客专家 Java Redis 架构 微信公众号:溪源的奇思妙想 溪源,一个在IT技术圈和经济学之间的求知者——既对人工智能、物联网等前沿技术兴致勃勃,又对机会成本、边际收益等经济学理论流连忘返。人生是一场孤独的旅行,只是我还是侥幸期待有同路人,我希望认识同样热爱技术、迷恋经济学的你。