TreeSet的使用方法和注意事项
来源:互联网 发布:py是什么意思网络语言 编辑:程序博客网 时间:2024/05/02 06:09
Set的子接口SortedSet,TreeSet实现了SortedSet。
TreeSet是无序的。
a)
public static void main(String[] args) { TreeSet set = new TreeSet(); set.add("A"); set.add("B"); set.add("C"); set.add("D"); set.add("E"); set.add("F"); System.out.println(set); }}
有程序可知,TreeSet可以自动把有序的序列排序。(对于一些无序的对象以及自定义的对象是无法自动排序的。同时会抛出ClassCastException异常,解决方法看下面的例子)
b)
public class TestTreeSet { public static void main(String[] args) { TreeSet set = new TreeSet(new MyCompare()); set.add("A"); set.add("B"); set.add("C"); set.add("D"); set.add("E"); set.add("F"); System.out.println(set); }} class MyCompare implements Comparator{ @Override publicint compare(Object o1,Object o2) { Strings1 = (String)o1; Strings2 = (String)o2; return s2.compareTo(s1); //return -s1.compareTo(s2); }}
TressSet通过构造方法TreeSet(Comparator<?superE>comparator)指定比较器。
如果想把数据逆序,可直接在compare方法中实现,上述代码既是实现字符的逆序。
C)关于对象的比较
public class TestTreeSet1 { public static void main(String[] args) { TreeSet set = new TreeSet(new MyCompare()); People p2 = new People(20); People p3 = new People(10); People p4 = new People(30); People p1 =new People(40); set.add(p1); set.add(p2); set.add(p3); set.add(p4); for(Iterator it =set.iterator(); it.hasNext();){ Peoplep = (People)it.next(); System.out.println(p.score); } }} class People{ int score; People(int score){ this.score = score; } } class MyCompare implements Comparator{ @Override publicint compare(Object o1,Object o2) { People p1 = (People)o1; People p2 = (People)o2; return p1.score - p2.score; } }
====================个人建议:分析代码时,请参考API,有助于理解=====================
- TreeSet的使用方法和注意事项
- TreeSet的使用方法和案例详解
- CTE的使用方法和注意事项
- cvFloodFill的使用方法和注意事项。
- BufferedReader的使用方法和注意事项
- cookie的使用方法和注意事项
- C++ typename 关键字的使用方法和注意事项
- 软件开发SVN的使用方法和注意事项
- onPause()和onStop()的使用方法及注意事项
- BufferedWriter的使用方法分和注意事项
- 标准光源箱的使用方法和注意事项
- break 和 continue 的使用方法及注意事项
- QThread 的使用方法 注意事项
- C++中typename关键字的使用方法和注意事项
- C++中typename关键字的使用方法和注意事项
- C++中typename关键字的使用方法和注意事项
- C++中typename关键字的使用方法和注意事项
- C++中typename关键字的使用方法和注意事项
- 旋转卡壳——凸多边形的宽度
- Flash player 11.2鼠标右键、中键 事件范例
- AnkhSvn安装后 VS2010中没有Subversion
- 测测你的金钱观爱情观事业观
- php算法汇总
- TreeSet的使用方法和注意事项
- 织梦dedecms模板乱码解决方法
- HTTP Content-type对照表
- 凸多边形间最小距离
- IplImage的初步使用
- java.sql.SQLException: JZ006: Caught IO Exception: java.net.SocketTimeoutException: Read timed out
- 《梦回水浒》玩家交流QQ群
- 凸多边形间最大距离
- Android系统自带样式(@android:style/)