1 /*
2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4  *
5  *
6  *
7  *
8  *
9  *
10  *
11  *
12  *
13  *
14  *
15  *
16  *
17  *
18  *
19  *
20  *
21  *
22  *
23  *
24  */

25
26 package java.util;
27
28 import java.io.InvalidObjectException;
29 import sun.misc.SharedSecrets;
30
31 /**
32  * This class implements the <tt>Set</tt> interface, backed by a hash table
33  * (actually a <tt>HashMap</tt> 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 <tt>null</tt>
36  * element.
37  *
38  * <p>This class offers constant time performance for the basic operations
39  * (<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>),
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 <tt>HashSet</tt> instance's size (the number of elements) plus the
43  * "capacity" of the backing <tt>HashMap</tt> 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 <tt>iterator</tt> 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 <tt>remove</tt>
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 <tt>ConcurrentModificationException</tt> 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}/../technotes/guides/collections/index.html">
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 <tt>HashMap</tt> 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 <tt>HashMap</tt> 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 <tt>HashMap</tt> 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 <tt>HashMap</tt> 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 intfloat 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 <tt>true</tt> if this set contains no elements.
187      *
188      * @return <tt>true</tt> if this set contains no elements
189      */

190     public boolean isEmpty() {
191         return map.isEmpty();
192     }
193
194     /**
195      * Returns <tt>true</tt> if this set contains the specified element.
196      * More formally, returns <tt>true</tt> if and only if this set
197      * contains an element <tt>e</tt> such that
198      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
199      *
200      * @param o element whose presence in this set is to be tested
201      * @return <tt>true</tt> 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 <tt>e</tt> to this set if
210      * this set contains no element <tt>e2</tt> such that
211      * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
212      * If this set already contains the element, the call leaves the set
213      * unchanged and returns <tt>false</tt>.
214      *
215      * @param e element to be added to this set
216      * @return <tt>true</tt> 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 <tt>e</tt> such that
226      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
227      * if this set contains such an element.  Returns <tt>true</tt> 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 <tt>true</tt> 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 <tt>HashSet</tt> 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 <tt>HashSet</tt> instance to a stream (that is,
266      * serialize it).
267      *
268      * @serialData The capacity of the backing <tt>HashMap</tt> 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 <tt>HashSet</tt> 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         // Set the capacity according to the size and load factor ensuring that
321         // the HashMap is at least 25% full but clamping to maximum capacity.
322         capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
323                 HashMap.MAXIMUM_CAPACITY);
324
325         // Constructing the backing map will lazily create an array when the first element is
326         // added, so check it before construction. Call HashMap.tableSizeFor to compute the
327         // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
328         // what is actually created.
329
330         SharedSecrets.getJavaOISAccess()
331                      .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
332
333         // Create backing HashMap
334         map = (((HashSet<?>)thisinstanceof LinkedHashSet ?
335                new LinkedHashMap<E,Object>(capacity, loadFactor) :
336                new HashMap<E,Object>(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<E,Object>(map, 0, -1, 0, 0);
360     }
361 }
362
Powered by JavaMelody