1 /*
2  * Copyright (c) 1997, 2023, 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.access.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     @java.io.Serial
95     static final long serialVersionUID = -5024744406713321676L;
96 
97     transient HashMap<E,Object> map;
98 
99     // Dummy value to associate with an Object in the backing Map
100     static final Object PRESENT = new Object();
101 
102     /**
103      * Constructs a new, empty set; the backing {@code HashMap} instance has
104      * default initial capacity (16) and load factor (0.75).
105      */
HashSet()106     public HashSet() {
107         map = new HashMap<>();
108     }
109 
110     /**
111      * Constructs a new set containing the elements in the specified
112      * collection.  The {@code HashMap} is created with default load factor
113      * (0.75) and an initial capacity sufficient to contain the elements in
114      * the specified collection.
115      *
116      * @param c the collection whose elements are to be placed into this set
117      * @throws NullPointerException if the specified collection is null
118      */
HashSet(Collection<? extends E> c)119     public HashSet(Collection<? extends E> c) {
120         map = HashMap.newHashMap(Math.max(c.size(), 12));
121         addAll(c);
122     }
123 
124     /**
125      * Constructs a new, empty set; the backing {@code HashMap} instance has
126      * the specified initial capacity and the specified load factor.
127      *
128      * @apiNote
129      * To create a {@code HashSet} with an initial capacity that accommodates
130      * an expected number of elements, use {@link #newHashSet(int) newHashSet}.
131      *
132      * @param      initialCapacity   the initial capacity of the hash map
133      * @param      loadFactor        the load factor of the hash map
134      * @throws     IllegalArgumentException if the initial capacity is less
135      *             than zero, or if the load factor is nonpositive
136      */
HashSet(int initialCapacity, float loadFactor)137     public HashSet(int initialCapacity, float loadFactor) {
138         map = new HashMap<>(initialCapacity, loadFactor);
139     }
140 
141     /**
142      * Constructs a new, empty set; the backing {@code HashMap} instance has
143      * the specified initial capacity and default load factor (0.75).
144      *
145      * @apiNote
146      * To create a {@code HashSet} with an initial capacity that accommodates
147      * an expected number of elements, use {@link #newHashSet(int) newHashSet}.
148      *
149      * @param      initialCapacity   the initial capacity of the hash table
150      * @throws     IllegalArgumentException if the initial capacity is less
151      *             than zero
152      */
HashSet(int initialCapacity)153     public HashSet(int initialCapacity) {
154         map = new HashMap<>(initialCapacity);
155     }
156 
157     /**
158      * Constructs a new, empty linked hash set.  (This package private
159      * constructor is only used by LinkedHashSet.) The backing
160      * HashMap instance is a LinkedHashMap with the specified initial
161      * capacity and the specified load factor.
162      *
163      * @param      initialCapacity   the initial capacity of the hash map
164      * @param      loadFactor        the load factor of the hash map
165      * @param      dummy             ignored (distinguishes this
166      *             constructor from other int, float constructor.)
167      * @throws     IllegalArgumentException if the initial capacity is less
168      *             than zero, or if the load factor is nonpositive
169      */
HashSet(int initialCapacity, float loadFactor, boolean dummy)170     HashSet(int initialCapacity, float loadFactor, boolean dummy) {
171         map = new LinkedHashMap<>(initialCapacity, loadFactor);
172     }
173 
174     /**
175      * Returns an iterator over the elements in this set.  The elements
176      * are returned in no particular order.
177      *
178      * @return an Iterator over the elements in this set
179      * @see ConcurrentModificationException
180      */
iterator()181     public Iterator<E> iterator() {
182         return map.keySet().iterator();
183     }
184 
185     /**
186      * Returns the number of elements in this set (its cardinality).
187      *
188      * @return the number of elements in this set (its cardinality)
189      */
size()190     public int size() {
191         return map.size();
192     }
193 
194     /**
195      * Returns {@code true} if this set contains no elements.
196      *
197      * @return {@code true} if this set contains no elements
198      */
isEmpty()199     public boolean isEmpty() {
200         return map.isEmpty();
201     }
202 
203     /**
204      * Returns {@code true} if this set contains the specified element.
205      * More formally, returns {@code true} if and only if this set
206      * contains an element {@code e} such that
207      * {@code Objects.equals(o, e)}.
208      *
209      * @param o element whose presence in this set is to be tested
210      * @return {@code true} if this set contains the specified element
211      */
contains(Object o)212     public boolean contains(Object o) {
213         return map.containsKey(o);
214     }
215 
216     /**
217      * Adds the specified element to this set if it is not already present.
218      * More formally, adds the specified element {@code e} to this set if
219      * this set contains no element {@code e2} such that
220      * {@code Objects.equals(e, e2)}.
221      * If this set already contains the element, the call leaves the set
222      * unchanged and returns {@code false}.
223      *
224      * @param e element to be added to this set
225      * @return {@code true} if this set did not already contain the specified
226      * element
227      */
add(E e)228     public boolean add(E e) {
229         return map.put(e, PRESENT)==null;
230     }
231 
232     /**
233      * Removes the specified element from this set if it is present.
234      * More formally, removes an element {@code e} such that
235      * {@code Objects.equals(o, e)},
236      * if this set contains such an element.  Returns {@code true} if
237      * this set contained the element (or equivalently, if this set
238      * changed as a result of the call).  (This set will not contain the
239      * element once the call returns.)
240      *
241      * @param o object to be removed from this set, if present
242      * @return {@code true} if the set contained the specified element
243      */
remove(Object o)244     public boolean remove(Object o) {
245         return map.remove(o)==PRESENT;
246     }
247 
248     /**
249      * Removes all of the elements from this set.
250      * The set will be empty after this call returns.
251      */
clear()252     public void clear() {
253         map.clear();
254     }
255 
256     /**
257      * Returns a shallow copy of this {@code HashSet} instance: the elements
258      * themselves are not cloned.
259      *
260      * @return a shallow copy of this set
261      */
262     @SuppressWarnings("unchecked")
clone()263     public Object clone() {
264         try {
265             HashSet<E> newSet = (HashSet<E>) super.clone();
266             newSet.map = (HashMap<E, Object>) map.clone();
267             return newSet;
268         } catch (CloneNotSupportedException e) {
269             throw new InternalError(e);
270         }
271     }
272 
273     /**
274      * Save the state of this {@code HashSet} instance to a stream (that is,
275      * serialize it).
276      *
277      * @serialData The capacity of the backing {@code HashMap} instance
278      *             (int), and its load factor (float) are emitted, followed by
279      *             the size of the set (the number of elements it contains)
280      *             (int), followed by all of its elements (each an Object) in
281      *             no particular order.
282      */
283     @java.io.Serial
writeObject(java.io.ObjectOutputStream s)284     private void writeObject(java.io.ObjectOutputStream s)
285         throws java.io.IOException {
286         // Write out any hidden serialization magic
287         s.defaultWriteObject();
288 
289         // Write out HashMap capacity and load factor
290         s.writeInt(map.capacity());
291         s.writeFloat(map.loadFactor());
292 
293         // Write out size
294         s.writeInt(map.size());
295 
296         // Write out all elements in the proper order.
297         for (E e : map.keySet())
298             s.writeObject(e);
299     }
300 
301     /**
302      * Reconstitute the {@code HashSet} instance from a stream (that is,
303      * deserialize it).
304      */
305     @java.io.Serial
readObject(java.io.ObjectInputStream s)306     private void readObject(java.io.ObjectInputStream s)
307         throws java.io.IOException, ClassNotFoundException {
308         // Consume and ignore stream fields (currently zero).
309         s.readFields();
310 
311         // Read capacity and verify non-negative.
312         int capacity = s.readInt();
313         if (capacity < 0) {
314             throw new InvalidObjectException("Illegal capacity: " +
315                                              capacity);
316         }
317 
318         // Read load factor and verify positive and non NaN.
319         float loadFactor = s.readFloat();
320         if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
321             throw new InvalidObjectException("Illegal load factor: " +
322                                              loadFactor);
323         }
324         // Clamp load factor to range of 0.25...4.0.
325         loadFactor = Math.clamp(loadFactor, 0.25f, 4.0f);
326 
327         // Read size and verify non-negative.
328         int size = s.readInt();
329         if (size < 0) {
330             throw new InvalidObjectException("Illegal size: " + size);
331         }
332 
333         // Set the capacity according to the size and load factor ensuring that
334         // the HashMap is at least 25% full but clamping to maximum capacity.
335         capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
336                 HashMap.MAXIMUM_CAPACITY);
337 
338         // Constructing the backing map will lazily create an array when the first element is
339         // added, so check it before construction. Call HashMap.tableSizeFor to compute the
340         // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
341         // what is actually created.
342         SharedSecrets.getJavaObjectInputStreamAccess()
343                      .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
344 
345         // Create backing HashMap
346         map = (this instanceof LinkedHashSet ?
347                new LinkedHashMap<>(capacity, loadFactor) :
348                new HashMap<>(capacity, loadFactor));
349 
350         // Read in all elements in the proper order.
351         for (int i=0; i<size; i++) {
352             @SuppressWarnings("unchecked")
353                 E e = (E) s.readObject();
354             map.put(e, PRESENT);
355         }
356     }
357 
358     /**
359      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
360      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
361      * set.
362      *
363      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
364      * {@link Spliterator#DISTINCT}.  Overriding implementations should document
365      * the reporting of additional characteristic values.
366      *
367      * @return a {@code Spliterator} over the elements in this set
368      * @since 1.8
369      */
spliterator()370     public Spliterator<E> spliterator() {
371         return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0);
372     }
373 
374     @Override
toArray()375     public Object[] toArray() {
376         return map.keysToArray(new Object[map.size()]);
377     }
378 
379     @Override
toArray(T[] a)380     public <T> T[] toArray(T[] a) {
381         return map.keysToArray(map.prepareArray(a));
382     }
383 
384     /**
385      * Creates a new, empty HashSet suitable for the expected number of elements.
386      * The returned set uses the default load factor of 0.75, and its initial capacity is
387      * generally large enough so that the expected number of elements can be added
388      * without resizing the set.
389      *
390      * @param numElements    the expected number of elements
391      * @param <T>         the type of elements maintained by the new set
392      * @return the newly created set
393      * @throws IllegalArgumentException if numElements is negative
394      * @since 19
395      */
newHashSet(int numElements)396     public static <T> HashSet<T> newHashSet(int numElements) {
397         if (numElements < 0) {
398             throw new IllegalArgumentException("Negative number of elements: " + numElements);
399         }
400         return new HashSet<>(HashMap.calculateHashMapCapacity(numElements));
401     }
402 
403 }
404