1、建立TreeSet實例java
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); }
輸出ide
[A, B, C, D, F]
輸出是有序的。this
2、TreeSet實例,按字符倒敘排列blog
實現了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); } }
打印:io
[F, D, C, B, A]class
3、按數字倒敘排列List
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); } }
打印結果im
[100, 70, 60, 50]sort
4、使用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]