TreeSet排序树
来源:互联网 发布:前端数据渲染 编辑:程序博客网 时间:2024/06/05 07:59
TreeSet中的对象是按照大小进行排序的,因此,TreeSet中的对象必须是可以比较大小的。
①可以通过TreeSet中的对象继承Comparable接口
②通过外部裁判来对对象进行大小裁定
根据自定义比较器的规则,当比较的对象相同,则认为是内容上或逻辑上相同的元素,就不会把他们加进来。
方式1:实现Comparable接口
package cn.cqu.huang;import java.util.Set;import java.util.TreeSet;class Student implements Comparable<Student>{ private String name; private int age; public Student(String name,int age){ this.name = name; this.age = age; } public String toString(){ return name+":"+age; } @Override public int compareTo(Student stu) { int t = name.compareTo(stu.name); if(t!=0) return t; //说明比较有了结果,直接返回 return this.age - stu.age; //当t为0时,说明name大小事相等的,因此需进一步根据年龄来区分大小 }}public class TreeSetDemo { public static void main(String[] args) { Set<Student> set = new TreeSet<Student>(); set.add(new Student("huang",10)); set.add(new Student("huang",20)); set.add(new Student("he",10)); set.add(new Student("huang",10)); set.add(new Student("yi",20)); System.out.println(set); }}
//方式2,使用裁判类
package cn.cqu.huang;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;class Student { private String name; private int age; public Student(String name,int age){ this.name = name; this.age = age; } public String getName(){ return name; } public int getAge(){ return age; } public String toString(){ return name+":"+age; }}//------------------裁判类class K implements Comparator{ @Override public int compare(Object obj1, Object obj2) { if(obj1 instanceof Student ==false || obj2 instanceof Student == false) return 0; Student s1 = (Student) obj1; Student s2 = (Student) obj2; int t = s1.getName().compareTo(s2.getName()); if(t!=0) return t; //t不为0,说明name不相同,已经比较出了结果 return s1.getAge()-s2.getAge();//name相同,则进一步比较年龄 }}public class TreeSetDemo { public static void main(String[] args) { Set<Student> set = new TreeSet<Student>(new K());//在构造TreeSet时传入一个裁判 set.add(new Student("huang",10)); set.add(new Student("huang",20)); set.add(new Student("he",10)); set.add(new Student("huang",10)); set.add(new Student("yi",20)); System.out.println(set); }}
运行结果如下:
0 0
- TreeSet排序树
- TreeSet排序
- TreeSet 排序
- TreeSet排序
- TreeSet 排序
- 使用TreeSet()进行排序
- 总结TreeSet排序问题
- TreeSet进行中文排序
- TreeSet排序总结
- TreeSet实现排序(二)
- TreeSet实现排序(一)
- TreeSet排序问题
- 总结TreeSet排序问题
- TreeSet自然排序
- TreeSet的排序
- TreeSet实现自定义排序
- 总结TreeSet排序问题 .
- TreeSet排序Comparator
- 二维数组右上左下遍历(C程序设计进阶第5周)
- WPS for Linux 提示字体缺失的处理办法
- 作为股权类投资人,我们的投资偏好和投资原则
- Linux的touch命令使用
- 牛客网 | 表示数值的字符串
- TreeSet排序树
- C#if if else笔记
- HDU ACM 1051 Wooden Sticks
- 树形结构的数据库实现,存储过程实现添加删除查询功能
- linux mysql免安装版
- HDU 4764 Stone(博弈)
- linux系统查看、修改IP、网关、DNS的方法
- WebKit之NPAPI插件
- 文字排版(C程序设计进阶第5周)