TreeSet集合添加自定义类的自然排序实例
2016-08-01 20:14
309 查看
如果自定义的类想要添加到TreeSet集合中就必须 实现 Comparable 或者 Comparator,如果实现Comparable 就是自然排序,Comparator 就是 定制排序
自然排序的步骤
1 定义bean类 实现Comparable接口并且重写 compareTo方法
2 测试类进行测试。
自然排序的步骤
1 定义bean类 实现Comparable接口并且重写 compareTo方法
2 测试类进行测试。
public class Test { public static void main(String[] args) { long l = System.currentTimeMillis(); TreeSet<Mark> set = new TreeSet<Mark>(); set.add(new Mark("张三", 11, 88)); set.add(new Mark("李四", 11, 98)); set.add(new Mark("王五", 11, 8)); long l2 = System.currentTimeMillis(); System.out.println(set); System.out.println("运行时间为"+(l2-l)); } } class Mark implements Comparable<Mark> { String name; int age; int count; public Mark(String name, int age, int count) { super(); this.name = name; this.age = age; this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public String toString() { return "Mark [age=" + age + ", count=" + count + ", name=" + name + "]"; } @Override public int compareTo(Mark o) { if (this.count > o.count) { return -1; } else if (this.count < o.count) { return 1; } else { if (this.age > o.age) { return 1; } else if (this.age < age) { return -1; } else { CollationKey key = Collator.getInstance().getCollationKey( this.name); CollationKey key1 = Collator.getInstance().getCollationKey( o.name); return key.compareTo(key1); } } } }
相关文章推荐
- html日记——使用强大的BootStrap(1)
- [LeetCode] 71. Simplify Path
- js 字符串加密
- Nginx - Events Module
- Python操作SQLAlchemy之连表操作
- 第四章-文件管理
- POJ:2914 Minimum Cut(暴力枚举并查集)
- 欢迎使用CSDN-markdown编辑器
- PHP之时区设置
- 暑期dp46道(8)--HDOJ 1506 Largest Rectangle in a Histogram
- C++ 输入流
- 从View向Controller传递复杂类型Json
- 不考虑花色情况下的炸金花扑克牌比大小
- CDOJ 1152 小panpan学图论 Floyd
- 二叉搜索树的后序遍历序列
- 排序
- 实用工具:VS上python开发插件(python tools for visual studio)
- HDU-2120-Ice_cream's world I【并查集】
- 使用Windows API进行GDI窗口绘图
- ActiveMQ学习(四)企业级应用配置详解