一、创建TreeSet实例

public static void main(String[] args) {
TreeSet set = new TreeSet(); set.add("C");
set.add("B");
set.add("A");
set.add("F");
set.add("D");
System.out.println(set);
}

  输出

[A, B, C, D, F]

  输出是有序的。

二、TreeSet实例,按字符倒叙排列

实现了Comparator接口

public class TreeSetTest3 {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet(new MyComparator() );
set.add("C");
set.add("B");
set.add("A");
set.add("F");
set.add("D");
System.out.println(set); }
} class MyComparator implements Comparator{ public int compare(Object o1, Object o2) { String s1 = (String) o1;
String s2 = (String) o2; return s2.compareTo(s1);
} }

  打印:

[F, D, C, B, A]

三、按数字倒叙排列

public class TreeSetTest2 {

	public static void main(String[] args) {
TreeSet set= new TreeSet(new Comparator() { public int compare(Object o1, Object o2) {
int i1 = ((Person) o1).score;
int i2 = ((Person) o2).score;
return i2 - i1;
} });
Person p1 = new Person(100);
Person p2 = new Person(60);
Person p3 = new Person(70);
Person p4 = new Person(50); set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
System.out.println(set);
}
} class Person{ int score; public Person(int score){
this.score = score;
} @Override
public String toString() { return String.valueOf(this.score);
}
}

  打印结果

[100, 70, 60, 50]

四、使用Collections降序

public class CollectionsTest {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(new Integer(5));
list.add(new Integer(25));
list.add(new Integer(15));
list.add(new Integer(35));
list.add(new Integer(1));
Comparator r = Collections.reverseOrder();
Collections.sort(list, r);
System.out.println(list); }
}

  [35, 25, 15, 5, 1]

最新文章

  1. magento的url中 去掉多余的目录层级
  2. Using Redis to store php session
  3. hdu 1003 MAX SUM 简单的dp,测试样例之间输出空行
  4. 【转】NumPy-快速处理数据
  5. 用c#开发微信 (14) 微统计 - 阅读分享统计系统 4 部署测试 (最终效果图)
  6. unix基本命令日记
  7. Swift语法总结补充(一)
  8. 一次DB2数据库连接失败(SQLSTATE=08001)的解决方法
  9. innodb_fast_shutdown中值为1或者2的区别是?
  10. Android开发-API指南-&lt;application&gt;
  11. sqlite3中的数据类型
  12. HDU 1540 / POJ 2892 Tunnel Warfare (单点更新,区间合并,求包含某点的最大连续个数)
  13. Linux C编程--格式化I/O
  14. 关于 addEventListener 和 handleEvent 方法
  15. 使用SndPlaySound从内存中播放WAV
  16. ios之TableViewCell重用机制避免反复显示问题
  17. [js高手之路] html5 canvas系列教程 - 像素操作(反色,黑白,亮度,复古,蒙版,透明)
  18. linux中使用Python IDE pycharm教程
  19. 115个Java面试题和答案——终极列表(下)【转】
  20. 如何在element-UI 组件的change事件中传递自定义参数

热门文章

  1. /proc路径
  2. H3C 802.11n
  3. 【转】TCP/IP协议详解 卷1
  4. LAMP环境源码编译安装过程
  5. com.mysql.jdbc.Driver not loaded. Are you sure you&#39;ve included the correct jdbc driver in :jdbc_driver_library?
  6. TOPk实现(python)
  7. SpringBoot -生成Entity和Dto互转的双向枚举类 -使用注解@Mapper(componentModel = &quot;spring&quot;)
  8. 关于Spring的常用注解和接口
  9. Spring源码窥探之:Spring AOP初步使用
  10. 快速开平方取倒数的算法--嵌入式ARM转载