使用TreeSet
来源:互联网 发布:淘宝卖家心酸 编辑:程序博客网 时间:2024/04/24 10:12
使用TreeSet必须传入比较器方法,常见有两种方式:
1.实现Comparable接口中compareTo方法
例:
/**main**/
TreeSet set=new TreeSet();
//若想添加Person元素信息,需要让Person类实现Comparable接口
set.add(new Person("Lambo",18));
/**Person**/
public class Person implements Comparable{
....
....
@Override
public int compareTo(Object o){
if(o instanceof Person){
Person person=(Person) o;
//返回负数为倒序
return XXX;
} else{
throw new ClassCastException("类型不可转换 ");
}
}
}
2.实现Comparator接口中compare方法
例:
Comparator comparator=new Comparator(){
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Person&&o2 instanceof Person ){
Person p1=(Person ) o1;
Person p2=(Person ) o2;
//返回负数为倒序
return XXXX;
}else
{
throw new ClassCastException("类型不可转换 ");
}
}
};
TreeSet set=new TreeSet(comparator );
*注:由于是排序集合,所以应该传入对象都是同一个类对象。
0 0
- TreeSet使用
- 使用TreeSet
- 使用TreeSet()进行排序
- TreeSet 使用举例
- java TreeSet的使用
- TreeSet的使用。
- java TreeSet的使用
- TreeSet的使用
- java TreeSet的使用
- java TreeSet的使用
- java TreeSet的使用
- TreeSet的使用
- Day13---TreeSet的使用
- java: TreeSet的使用
- TreeSet()原理及使用
- TreeSet的使用
- 集合TreeSet的使用
- TreeSet的使用
- 遍历集合
- 如何消除内存泄漏
- Java写爬虫
- ACM-约瑟夫问题
- 计划
- 使用TreeSet
- PAT L2-003
- [2017/3/13]阿里面试总结
- linux命令 cat <<- _EOF_ 输出多行文本
- POJ2112-Optimal Milking
- 数组冒泡
- ssh连接慢
- MQTT---HiveMQ源码详解(十七)Cluster-Consistent Hashing Ring & Node Lifecycle
- 使用及自定义泛型