Step By Step(Java 集合篇) (六)

2014-11-24 03:19:39 · 作者: · 浏览: 6
ashSet);

69 //set之后的并发操作将不再需要synchronized关键字来进行同步了。

70 }

7. TreeSet:该集合为有序集合,数据在插入集合后便按照自定义的排序规则将插入的对象进行排序,该集合主要是通过两种方式排序插入对象的,一种是要求集合元素类必须是Comparable的实现类,这样在插入对象的时候,集合可以根据compareTo方法的返回值来确定新插入对象的位置,另外一种方式是通过在构造该集合对象的时候,传入Comparator的实现类作为参数,之后所有插入的对象都是通过Comparator的compare方法的返回值来决定新对象的位置。该集合是通过RBTree(红黑树)来实现排序的,这一点和C++标准库中的set和map是一致的。由于对象插入集合之后是有序的,因此该集合的插入效率要低于HashSet的插入效率。TreeSet和HashSet相比主要的差异来自于对象的排序规则,以上HashSet的示例代码均适用于TreeSet,下面只是列出对象比较的代码:

1 public class Item implements Comparable {

2 public int compareTo(Item other) {

3 return partNumber - other.partNumber;

4 }

5 }

6 public static void main(String[] args) {

7 SortedSet parts = new TreeSet();

8 parts.add(new Item("Toaster",1234));

9 parts.add(new Item("Widget",4562));

10 parts.add(new Item("Modem",9912));

11 System.out.println(parts);

12

13 SortedSet sortByDescription = new TreeSet(new Comparator() {

14 public int compare(Item a,Item b) {

15 String descA = a.getDescription();

16 String descB = b.getDescription();

17 return descA.compareTo(descB);

18 }

19 });

20 sortByDescription.addAll(parts);

21 System.out.println(sortByDescription);

22 }

8. PriorityQueue(优先级对象): 该容器也是有序集合,和TreeSet不同的是,该集合只是保证当从集合的头部取出数据的时候,总是取出队列中最小(优先级最高)的元素。该集合内部是通过"堆"的数据结构实现的,该结构只有第一个元素(头部元素)保证为该集合中最大的或最小的元素,其余元素没有固定的顺序,但是当集合有新的对象从尾部插入或是从头部取出时,集合内部的相关元素会进行比较的比较最终再次决定出谁是最大或最小的元素作为头部元素。在JDK提供的classes中Timer是通过该数据结构实现的,从而保证了Timer每次获取任务时都是最应该被调度的TimerTask,见如下代码:

1 public class TestMain {

2 public static void main(String[] args) {

3 PriorityQueue pq = new PriorityQueue();

4 pq.add("1");

5 pq.add("6");

6 pq.add("4");

7 pq.offer("5");

8 pq.offer("3");

9 pq.offer("2");

10 pq.offer("7");

11 //以下输出将以无序的结果输出

12 System.out.println(pq);

13 //以下输出将以有序的结果输出

14 while (pq.peek() != null) {

15 String str = pq.poll();

16 System.out.println(str);

17 }

18 int initCapacity = 20;

19 PriorityQueue pq1 = new PriorityQueue(initCapacity,

20 new Comparator() {

21 public int compare(TestComparator t1, TestComparator t2) {

22 return t1.getID() - t2.getID();

23 }

24 });

25 pq1.offer(new TestComparator(1));

26 pq1.offer(new TestComparator(6));

27 pq1.offer(new TestComparator(4));

28 pq1.offer(new TestComparator(5));

29 pq1.offer(new TestComparator(3));

30 pq1.offer(new TestComparator(2));

31 pq1.offer(new TestComparator(7));

32 System.out.println("The following is for TestComparator.");

33 System.out.println(pq1);

34 while (pq1.peek() != null) {

35 int id = pq1.poll().getID();

36 System.out.println(id);

37