TreeSet的comparable接口
来源:互联网 发布:网络视频服务器使用 编辑:程序博客网 时间:2024/04/30 16:17
TreeSet是一个排序的、无重复元素的集合。
如果创建自定义对象,并且TreeSet创建时调用的是无参的构造函数,那么必须要实现comparable接口。
示例代码:向TreeSet中插入无参的自定义对象Persons(含name,age)。
注意:
1、首先要实现comparable接口
2、comparable接口内容要合理,比如只判断年龄进行排序,那么结果是年龄相同的所有Persons对象,将被视为是重复的,所以如果姓名也要按照字母顺序排序,那么也要在判断年龄相同时,给出判断name的情况,否则TreeSet将会视为重复元素,不予插入。
package test;import java.util.Iterator;import java.util.TreeSet;public class TestTreeSet { public static void main(String[] args) { TreeSet ts = new TreeSet<>(); ts.add(new Persons("java01",1)); ts.add(new Persons("java03",3)); ts.add(new Persons("java02",2)); ts.add(new Persons("java04",4)); ts.add(new Persons("java05",4)); for(Iterator it = ts.iterator();it.hasNext();){ System.out.println(it.next()); } }}class Persons implements Comparable{ String name; int age; Persons(String name,int age){ this.name = name; this.age = age; } 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; } @Override public int compareTo(Object obj) { if(!(obj instanceof Persons)) throw new RuntimeException(); Persons p = (Persons)obj; if((this.age-p.age) == 0) return this.name.compareTo(p.name); else return this.age-p.age; } @Override public String toString() { return "姓名:"+this.name+",年龄:"+this.age; }}
0 0
- TreeSet的comparable接口
- TreeSet结合Comparable接口的使用
- treeset的使用(Comparable接口和Compartor接口的使用)
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- treeSet添加的元素需要实现comparable接口,否则会出现 类型转换错误
- TreeSet是可以对字符串进行排序 的, 因为字符串已经实现了Comparable接口。
- java比较接口Comparable,对象排序存在TreeSet中
- HashSet TreeSet 和 equals、hashCode、comparable接口之间关联
- TreeSet实现Comparable接口覆写compareTo()方法
- Comparable接口的实现
- java的comparable 接口
- TreeSet集合存放自定义类型的对象,可以使用比较器,实现Comparable接口自己设置排序方式
- 黑马程序员-集合框架【TreeSet】、【二叉树】、【Comparable接口】、【Comparator接口】
- java学习笔记:利用TreeSet排序时Comparator接口和Comparable接口
- 由TreeSet引出的Comparable和Comparator学习小结
- Guibs 的 Python学习_ 函数
- lambda
- servlet涉及对象
- SQL语句
- gcc编译的背后
- TreeSet的comparable接口
- 2016.9.4
- mysql 导入txt文档的问题
- 字典树合并 ifrog1028 Bob and Alice are playing numbers
- Linux用户和群组基本命令
- 直接插入排序
- CD检测代码的定位练习-20160905
- C/C++开发者必不可少的15款编译器+IDE
- const关键字