1 /*
2 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.util;
27
28 import java.io.InvalidObjectException;
29 import jdk.internal.misc.SharedSecrets;
30
31 /**
32 * This class implements the {@code Set} interface, backed by a hash table
33 * (actually a {@code HashMap} instance). It makes no guarantees as to the
34 * iteration order of the set; in particular, it does not guarantee that the
35 * order will remain constant over time. This class permits the {@code null}
36 * element.
37 *
38 * <p>This class offers constant time performance for the basic operations
39 * ({@code add}, {@code remove}, {@code contains} and {@code size}),
40 * assuming the hash function disperses the elements properly among the
41 * buckets. Iterating over this set requires time proportional to the sum of
42 * the {@code HashSet} instance's size (the number of elements) plus the
43 * "capacity" of the backing {@code HashMap} instance (the number of
44 * buckets). Thus, it's very important not to set the initial capacity too
45 * high (or the load factor too low) if iteration performance is important.
46 *
47 * <p><strong>Note that this implementation is not synchronized.</strong>
48 * If multiple threads access a hash set concurrently, and at least one of
49 * the threads modifies the set, it <i>must</i> be synchronized externally.
50 * This is typically accomplished by synchronizing on some object that
51 * naturally encapsulates the set.
52 *
53 * If no such object exists, the set should be "wrapped" using the
54 * {@link Collections#synchronizedSet Collections.synchronizedSet}
55 * method. This is best done at creation time, to prevent accidental
56 * unsynchronized access to the set:<pre>
57 * Set s = Collections.synchronizedSet(new HashSet(...));</pre>
58 *
59 * <p>The iterators returned by this class's {@code iterator} method are
60 * <i>fail-fast</i>: if the set is modified at any time after the iterator is
61 * created, in any way except through the iterator's own {@code remove}
62 * method, the Iterator throws a {@link ConcurrentModificationException}.
63 * Thus, in the face of concurrent modification, the iterator fails quickly
64 * and cleanly, rather than risking arbitrary, non-deterministic behavior at
65 * an undetermined time in the future.
66 *
67 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
68 * as it is, generally speaking, impossible to make any hard guarantees in the
69 * presence of unsynchronized concurrent modification. Fail-fast iterators
70 * throw {@code ConcurrentModificationException} on a best-effort basis.
71 * Therefore, it would be wrong to write a program that depended on this
72 * exception for its correctness: <i>the fail-fast behavior of iterators
73 * should be used only to detect bugs.</i>
74 *
75 * <p>This class is a member of the
76 * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
77 * Java Collections Framework</a>.
78 *
79 * @param <E> the type of elements maintained by this set
80 *
81 * @author Josh Bloch
82 * @author Neal Gafter
83 * @see Collection
84 * @see Set
85 * @see TreeSet
86 * @see HashMap
87 * @since 1.2
88 */
89
90 public class HashSet<E>
91 extends AbstractSet<E>
92 implements Set<E>, Cloneable, java.io.Serializable
93 {
94 static final long serialVersionUID = -5024744406713321676L;
95
96 private transient HashMap<E,Object> map;
97
98 // Dummy value to associate with an Object in the backing Map
99 private static final Object PRESENT = new Object();
100
101 /**
102 * Constructs a new, empty set; the backing {@code HashMap} instance has
103 * default initial capacity (16) and load factor (0.75).
104 */
105 public HashSet() {
106 map = new HashMap<>();
107 }
108
109 /**
110 * Constructs a new set containing the elements in the specified
111 * collection. The {@code HashMap} is created with default load factor
112 * (0.75) and an initial capacity sufficient to contain the elements in
113 * the specified collection.
114 *
115 * @param c the collection whose elements are to be placed into this set
116 * @throws NullPointerException if the specified collection is null
117 */
118 public HashSet(Collection<? extends E> c) {
119 map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
120 addAll(c);
121 }
122
123 /**
124 * Constructs a new, empty set; the backing {@code HashMap} instance has
125 * the specified initial capacity and the specified load factor.
126 *
127 * @param initialCapacity the initial capacity of the hash map
128 * @param loadFactor the load factor of the hash map
129 * @throws IllegalArgumentException if the initial capacity is less
130 * than zero, or if the load factor is nonpositive
131 */
132 public HashSet(int initialCapacity, float loadFactor) {
133 map = new HashMap<>(initialCapacity, loadFactor);
134 }
135
136 /**
137 * Constructs a new, empty set; the backing {@code HashMap} instance has
138 * the specified initial capacity and default load factor (0.75).
139 *
140 * @param initialCapacity the initial capacity of the hash table
141 * @throws IllegalArgumentException if the initial capacity is less
142 * than zero
143 */
144 public HashSet(int initialCapacity) {
145 map = new HashMap<>(initialCapacity);
146 }
147
148 /**
149 * Constructs a new, empty linked hash set. (This package private
150 * constructor is only used by LinkedHashSet.) The backing
151 * HashMap instance is a LinkedHashMap with the specified initial
152 * capacity and the specified load factor.
153 *
154 * @param initialCapacity the initial capacity of the hash map
155 * @param loadFactor the load factor of the hash map
156 * @param dummy ignored (distinguishes this
157 * constructor from other int, float constructor.)
158 * @throws IllegalArgumentException if the initial capacity is less
159 * than zero, or if the load factor is nonpositive
160 */
161 HashSet(int initialCapacity, float loadFactor, boolean dummy) {
162 map = new LinkedHashMap<>(initialCapacity, loadFactor);
163 }
164
165 /**
166 * Returns an iterator over the elements in this set. The elements
167 * are returned in no particular order.
168 *
169 * @return an Iterator over the elements in this set
170 * @see ConcurrentModificationException
171 */
172 public Iterator<E> iterator() {
173 return map.keySet().iterator();
174 }
175
176 /**
177 * Returns the number of elements in this set (its cardinality).
178 *
179 * @return the number of elements in this set (its cardinality)
180 */
181 public int size() {
182 return map.size();
183 }
184
185 /**
186 * Returns {@code true} if this set contains no elements.
187 *
188 * @return {@code true} if this set contains no elements
189 */
190 public boolean isEmpty() {
191 return map.isEmpty();
192 }
193
194 /**
195 * Returns {@code true} if this set contains the specified element.
196 * More formally, returns {@code true} if and only if this set
197 * contains an element {@code e} such that
198 * {@code Objects.equals(o, e)}.
199 *
200 * @param o element whose presence in this set is to be tested
201 * @return {@code true} if this set contains the specified element
202 */
203 public boolean contains(Object o) {
204 return map.containsKey(o);
205 }
206
207 /**
208 * Adds the specified element to this set if it is not already present.
209 * More formally, adds the specified element {@code e} to this set if
210 * this set contains no element {@code e2} such that
211 * {@code Objects.equals(e, e2)}.
212 * If this set already contains the element, the call leaves the set
213 * unchanged and returns {@code false}.
214 *
215 * @param e element to be added to this set
216 * @return {@code true} if this set did not already contain the specified
217 * element
218 */
219 public boolean add(E e) {
220 return map.put(e, PRESENT)==null;
221 }
222
223 /**
224 * Removes the specified element from this set if it is present.
225 * More formally, removes an element {@code e} such that
226 * {@code Objects.equals(o, e)},
227 * if this set contains such an element. Returns {@code true} if
228 * this set contained the element (or equivalently, if this set
229 * changed as a result of the call). (This set will not contain the
230 * element once the call returns.)
231 *
232 * @param o object to be removed from this set, if present
233 * @return {@code true} if the set contained the specified element
234 */
235 public boolean remove(Object o) {
236 return map.remove(o)==PRESENT;
237 }
238
239 /**
240 * Removes all of the elements from this set.
241 * The set will be empty after this call returns.
242 */
243 public void clear() {
244 map.clear();
245 }
246
247 /**
248 * Returns a shallow copy of this {@code HashSet} instance: the elements
249 * themselves are not cloned.
250 *
251 * @return a shallow copy of this set
252 */
253 @SuppressWarnings("unchecked")
254 public Object clone() {
255 try {
256 HashSet<E> newSet = (HashSet<E>) super.clone();
257 newSet.map = (HashMap<E, Object>) map.clone();
258 return newSet;
259 } catch (CloneNotSupportedException e) {
260 throw new InternalError(e);
261 }
262 }
263
264 /**
265 * Save the state of this {@code HashSet} instance to a stream (that is,
266 * serialize it).
267 *
268 * @serialData The capacity of the backing {@code HashMap} instance
269 * (int), and its load factor (float) are emitted, followed by
270 * the size of the set (the number of elements it contains)
271 * (int), followed by all of its elements (each an Object) in
272 * no particular order.
273 */
274 private void writeObject(java.io.ObjectOutputStream s)
275 throws java.io.IOException {
276 // Write out any hidden serialization magic
277 s.defaultWriteObject();
278
279 // Write out HashMap capacity and load factor
280 s.writeInt(map.capacity());
281 s.writeFloat(map.loadFactor());
282
283 // Write out size
284 s.writeInt(map.size());
285
286 // Write out all elements in the proper order.
287 for (E e : map.keySet())
288 s.writeObject(e);
289 }
290
291 /**
292 * Reconstitute the {@code HashSet} instance from a stream (that is,
293 * deserialize it).
294 */
295 private void readObject(java.io.ObjectInputStream s)
296 throws java.io.IOException, ClassNotFoundException {
297 // Read in any hidden serialization magic
298 s.defaultReadObject();
299
300 // Read capacity and verify non-negative.
301 int capacity = s.readInt();
302 if (capacity < 0) {
303 throw new InvalidObjectException("Illegal capacity: " +
304 capacity);
305 }
306
307 // Read load factor and verify positive and non NaN.
308 float loadFactor = s.readFloat();
309 if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
310 throw new InvalidObjectException("Illegal load factor: " +
311 loadFactor);
312 }
313
314 // Read size and verify non-negative.
315 int size = s.readInt();
316 if (size < 0) {
317 throw new InvalidObjectException("Illegal size: " +
318 size);
319 }
320
321 // Set the capacity according to the size and load factor ensuring that
322 // the HashMap is at least 25% full but clamping to maximum capacity.
323 capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
324 HashMap.MAXIMUM_CAPACITY);
325
326 // Constructing the backing map will lazily create an array when the first element is
327 // added, so check it before construction. Call HashMap.tableSizeFor to compute the
328 // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
329 // what is actually created.
330 SharedSecrets.getJavaObjectInputStreamAccess()
331 .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
332
333 // Create backing HashMap
334 map = (((HashSet<?>)this) instanceof LinkedHashSet ?
335 new LinkedHashMap<>(capacity, loadFactor) :
336 new HashMap<>(capacity, loadFactor));
337
338 // Read in all elements in the proper order.
339 for (int i=0; i<size; i++) {
340 @SuppressWarnings("unchecked")
341 E e = (E) s.readObject();
342 map.put(e, PRESENT);
343 }
344 }
345
346 /**
347 * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
348 * and <em>fail-fast</em> {@link Spliterator} over the elements in this
349 * set.
350 *
351 * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
352 * {@link Spliterator#DISTINCT}. Overriding implementations should document
353 * the reporting of additional characteristic values.
354 *
355 * @return a {@code Spliterator} over the elements in this set
356 * @since 1.8
357 */
358 public Spliterator<E> spliterator() {
359 return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0);
360 }
361 }
362