1、TreeSet构造排序的集合
TreeSet类型是J2SE中唯一可实现自动排序的类型,用法如下:
MyComparator.java
1
package
test;
2
3 import java.util.Comparator;
4
5 public class MyComparator < T > implements Comparator < T > {
6
7 public int compare(T arg0, T arg1) {
8 if (arg0.equals(arg1)) {
9 return 0;
10 }
11 return ((Comparable<T>) arg0).compareTo(arg1) * -1;
12 }
13
14}
2
3 import java.util.Comparator;
4
5 public class MyComparator < T > implements Comparator < T > {
6
7 public int compare(T arg0, T arg1) {
8 if (arg0.equals(arg1)) {
9 return 0;
10 }
11 return ((Comparable<T>) arg0).compareTo(arg1) * -1;
12 }
13
14}
TreeSetTest.java
1
package
test;
2
3 import java.util.Iterator;
4 import java.util.TreeSet;
5
6 public class TreeSetTest {
7
8 /** *//**
9 * @param args
10 */
11 public static void main(String[] args) {
12
13 MyComparator<String> myComparator = new MyComparator<String>();
14
15 // /不添加自定义排序
16 TreeSet<String> treeSet1 = new TreeSet<String>();
17 treeSet1.add("c");
18 treeSet1.add("a");
19 treeSet1.add("b");
20
21 Iterator<String> iterator1 = treeSet1.iterator();
22 while (iterator1.hasNext()) {
23 System.out.println(iterator1.next());
24 }
25
26 // /添加自定义排序
27 TreeSet<String> treeSet2 = new TreeSet<String>(myComparator);
28 treeSet2.add("c");
29 treeSet2.add("a");
30 treeSet2.add("b");
31
32 Iterator<String> iterator2 = treeSet2.iterator();
33 while (iterator2.hasNext()) {
34 System.out.println(iterator2.next());
35 }
36 }
37
38}
39
2
3 import java.util.Iterator;
4 import java.util.TreeSet;
5
6 public class TreeSetTest {
7
8 /** *//**
9 * @param args
10 */
11 public static void main(String[] args) {
12
13 MyComparator<String> myComparator = new MyComparator<String>();
14
15 // /不添加自定义排序
16 TreeSet<String> treeSet1 = new TreeSet<String>();
17 treeSet1.add("c");
18 treeSet1.add("a");
19 treeSet1.add("b");
20
21 Iterator<String> iterator1 = treeSet1.iterator();
22 while (iterator1.hasNext()) {
23 System.out.println(iterator1.next());
24 }
25
26 // /添加自定义排序
27 TreeSet<String> treeSet2 = new TreeSet<String>(myComparator);
28 treeSet2.add("c");
29 treeSet2.add("a");
30 treeSet2.add("b");
31
32 Iterator<String> iterator2 = treeSet2.iterator();
33 while (iterator2.hasNext()) {
34 System.out.println(iterator2.next());
35 }
36 }
37
38}
39
运行结果:
a
b
c
c
b
a
b
c
c
b
a
参考:http://www.blogjava.net/ITdavid/archive/2008/02/27/182478.html