TreeMap
来源:互联网 发布:fragment重新加载数据 编辑:程序博客网 时间:2024/06/17 20:50
TreeMap
基于红黑树结果
俩种排序方式:
自然排序 :实现Comparable接口,需要重写compareTo方法 比较器排序 :Comparaor(重写compare方法)
需求:
输入学生类 ,姓名和年龄 ,String类朝代,并排序
代码:
public static void main(String[] args) { TreeMap<Student,String> tm = new TreeMap<Student,String>(new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { int num = o1.getAge()-o2.getAge(); int num2 =num ==0? o1.getName().compareTo(o2.getName()): num ; return num2; } }); //创建学生对象 Student s1 = new Student("潘安", 20) ; Student s2 = new Student("柳下惠", 25) ; Student s3 = new Student("唐伯虎", 33) ; Student s4 = new Student("李清照", 33) ; Student s5 = new Student("唐伯虎", 33) ; //给集合中添加元素 tm.put(s1, "宋朝") ; tm.put(s2, "元朝") ; tm.put(s3, "明朝") ; tm.put(s4, "宋朝") ; tm.put(s5, "汉朝") ; Set<Student> keySet = tm.keySet(); for(Student s :keySet){ String string = tm.get(s); System.out.println(s.getName()+"---"+s.getAge()+"---"+string); }}
结果:
潘安—20—宋朝
柳下惠—25—元朝
唐伯虎—33—汉朝
李清照—33—宋朝
阅读全文
0 0
- TreeMap
- TreeMap
- treeMap
- TreeMap
- TreeMap
- TreeMap
- TreeMap
- TreeMap
- TreeMap
- treemap
- treemap
- TreeMap
- TreeMap
- treemap
- -TreeMap
- TreeMap
- treemap
- TreeMap
- hdu 1156
- JS不靠谱系列之枚举出时间段和对应的分钟数
- JS
- ORM 和 JDBC 的区别
- PHP用mysqli来连接数据库
- TreeMap
- 2017.8.10
- Collections
- hi
- Visual C# 数据绑定
- 12345
- 异常(捕获异常)
- C. Beautiful Set----枚举
- L2-020. 功夫传人