一、创建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]