1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package ch.elca.el4j.util.collections;
22
23 import java.util.*;
24 import java.util.Map.Entry;
25
26
27
28
29
30
31 public class IdentityHashSet<E> implements Set<E> {
32
33 IdentityHashMap<E, Object> map = new IdentityHashMap<E, Object>();
34
35 public boolean add(E element) {
36 if (map.containsKey(element)) {
37 return false;
38 } else {
39 map.put(element, null);
40 return true;
41 }
42 }
43
44 public boolean addAll(Collection<? extends E> elements) {
45 boolean anyChanges = false;
46 for (E element : elements) {
47 if (!map.containsKey(element)) {
48 anyChanges = true;
49 map.put(element, null);
50 }
51 }
52 return anyChanges;
53 }
54
55 public void clear() {
56 map.clear();
57 }
58
59 public boolean contains(Object element) {
60 return map.containsKey(element);
61 }
62
63 public boolean containsAll(Collection<?> elements) {
64 for (Object element : elements) {
65 if (!map.containsKey(element)) return false;
66 }
67 return true;
68 }
69
70 public boolean isEmpty() {
71 return map.isEmpty();
72 }
73
74 public Iterator<E> iterator() {
75
76 return new Iterator<E>() {
77 Iterator<Map.Entry<E, Object>> it = map.entrySet().iterator();
78
79 public boolean hasNext() {
80 return it.hasNext();
81 }
82
83 public E next() {
84 return it.next().getKey();
85 }
86
87 public void remove() {
88 it.remove();
89 }
90 };
91 }
92
93 public boolean remove(Object element) {
94 if (map.containsKey(element)) {
95 map.remove(element);
96 return true;
97 } else {
98 return false;
99 }
100 }
101
102 public boolean removeAll(Collection<?> elements) {
103 for (Object element : elements) map.remove(element);
104 return true;
105 }
106
107 public boolean retainAll(Collection<?> elements) {
108 IdentityHashMap<E, Object> newMap = new IdentityHashMap<E, Object>();
109
110 for (Object element : elements) {
111 if (map.containsKey(element)) newMap.put((E) element, null);
112 }
113
114 boolean anyChanges = newMap.size() != map.size();
115
116 map = newMap;
117 return anyChanges;
118 }
119
120 public int size() {
121 return map.size();
122 }
123
124 public Object[] toArray() {
125 throw new UnsupportedOperationException("Unsupported operation on IdentityHashSet.");
126 }
127
128 public <T> T[] toArray(T[] dummy) {
129 throw new UnsupportedOperationException("Unsupported operation on IdentityHashSet.");
130 }
131
132 public String toString() {
133 StringBuffer buf = new StringBuffer();
134 buf.append("{");
135
136 Iterator<Entry<E, Object>> i = map.entrySet().iterator();
137 boolean hasNext = i.hasNext();
138 while (hasNext) {
139 Entry<E, Object> e = i.next();
140 E key = e.getKey();
141 buf.append(key);
142 hasNext = i.hasNext();
143 if (hasNext) {
144 buf.append(", ");
145 }
146 }
147
148 buf.append("}");
149 return buf.toString();
150 }
151
152 }