Java和C++在细节上的差异(四)(八)

2014-11-24 02:04:05 · 作者: · 浏览: 10
n(hSet);
21 booleanblnRemoved = hSet.remove(newInteger("2"));
22 System.out.println(hSet.contains(newInteger("2")));
23 System.out.println(blnRemoved);
24 System.out.println(hSet);
25 hSet.clear();
26 System.out.println(hSet);
27 System.out.println(hSet.isEmpty());
28 }
29
30 publicstaticvoidshowToArrayListAndArray() {
31 HashSet hs = newHashSet();
32 hs.add("B");
33 hs.add("A");
34 hs.add("D");
35 System.out.println(hs);
36 List list = newArrayList(hs);
37 Object[] objects = list.toArray();
38 for(Object obj : objects)
39 System.out.println("Object = " + obj);
40 String[] strs = list.toArray(newString[0]);
41 for(String str : strs)
42 System.out.println("String = " + str);
43 }
44
45 publicstaticvoidshowToHashSetAndRemoveDuplicate() {
46 Integer[] numbers = { 7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4 };
47 List list = Arrays.asList(numbers);
48 Set set = newHashSet(list);
49 for(Integer o : set)
50 System.out.print(o + ", ");
51 }
52
53 publicstaticvoidshowMinMax() {
54 HashSet hashSet = newHashSet();
55 hashSet.add(newLong("9"));
56 hashSet.add(newLong("4"));
57 hashSet.add(newLong("2"));
58 hashSet.add(newLong("2"));
59 hashSet.add(newLong("3"));
60 Object objMin = Collections.min(hashSet);
61 System.out.println("Minimum Element of Java HashSet is : " + objMin);
62 Object objMax = Collections.max(hashSet);
63 System.out.println("Maximum Element of Java HashSet is : "+ objMax);
64 }
65
66 publicstaticvoidshowSynchronizedSet() {
67 HashSet hashSet = newHashSet();
68 Set set = Collections.synchronizedSet(hashSet);
69 //set之后的并发操作将不再需要synchronized关键字来进行同步了。
70 }

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

1 publicclassItem implementsComparable {
2 publicintcompareTo(Item other) {
3 returnpartNumber - other.partNumber;
4 }
5 }
6 publicstaticvoidmain(String[] args) {
7 SortedSet parts = newTreeSet();
8 parts.add(newItem("Toaster",1234));
9 parts.add(newItem("Widget",4562));
10 parts.add(newItem("Modem",9912));
11 System.out.println(parts);
12
13 SortedSet sortByDescription = newTreeSet(newComparator() {
14 publicintcompare(Item a,Item b) {
15 String descA = a.getDescription();
16 String descB = b.getDescription();
17 returndescA.compareTo(descB);
18 }
19 });
20 sortByDescription.addAll(parts);
21 System.out.println(sortByDescription);
22 }

8. PriorityQueue(优先级对象): 该容器也是有序集合,和TreeSet不同的是,该集合只是保证当从集合的头部取出数据