001 /* HashSet.java -- a class providing a HashMap-backed Set
002 Copyright (C) 1998, 1999, 2001, 2004, 2005 Free Software Foundation, Inc.
003
004 This file is part of GNU Classpath.
005
006 GNU Classpath is free software; you can redistribute it and/or modify
007 it under the terms of the GNU General Public License as published by
008 the Free Software Foundation; either version 2, or (at your option)
009 any later version.
010
011 GNU Classpath is distributed in the hope that it will be useful, but
012 WITHOUT ANY WARRANTY; without even the implied warranty of
013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 General Public License for more details.
015
016 You should have received a copy of the GNU General Public License
017 along with GNU Classpath; see the file COPYING. If not, write to the
018 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019 02110-1301 USA.
020
021 Linking this library statically or dynamically with other modules is
022 making a combined work based on this library. Thus, the terms and
023 conditions of the GNU General Public License cover the whole
024 combination.
025
026 As a special exception, the copyright holders of this library give you
027 permission to link this library with independent modules to produce an
028 executable, regardless of the license terms of these independent
029 modules, and to copy and distribute the resulting executable under
030 terms of your choice, provided that you also meet, for each linked
031 independent module, the terms and conditions of the license of that
032 module. An independent module is a module which is not derived from
033 or based on this library. If you modify this library, you may extend
034 this exception to your version of the library, but you are not
035 obligated to do so. If you do not wish to do so, delete this
036 exception statement from your version. */
037
038
039 package java.util;
040
041 import java.io.IOException;
042 import java.io.ObjectInputStream;
043 import java.io.ObjectOutputStream;
044 import java.io.Serializable;
045
046 /**
047 * This class provides a HashMap-backed implementation of the Set interface.
048 * <p>
049 *
050 * Most operations are O(1), assuming no hash collisions. In the worst
051 * case (where all hashes collide), operations are O(n). Setting the
052 * initial capacity too low will force many resizing operations, but
053 * setting the initial capacity too high (or loadfactor too low) leads
054 * to wasted memory and slower iteration.
055 * <p>
056 *
057 * HashSet accepts the null key and null values. It is not synchronized,
058 * so if you need multi-threaded access, consider using:<br>
059 * <code>Set s = Collections.synchronizedSet(new HashSet(...));</code>
060 * <p>
061 *
062 * The iterators are <i>fail-fast</i>, meaning that any structural
063 * modification, except for <code>remove()</code> called on the iterator
064 * itself, cause the iterator to throw a
065 * {@link ConcurrentModificationException} rather than exhibit
066 * non-deterministic behavior.
067 *
068 * @author Jon Zeppieri
069 * @author Eric Blake (ebb9@email.byu.edu)
070 * @see Collection
071 * @see Set
072 * @see TreeSet
073 * @see Collections#synchronizedSet(Set)
074 * @see HashMap
075 * @see LinkedHashSet
076 * @since 1.2
077 * @status updated to 1.4
078 */
079 public class HashSet<T> extends AbstractSet<T>
080 implements Set<T>, Cloneable, Serializable
081 {
082 /**
083 * Compatible with JDK 1.2.
084 */
085 private static final long serialVersionUID = -5024744406713321676L;
086
087 /**
088 * The HashMap which backs this Set.
089 */
090 private transient HashMap<T, String> map;
091
092 /**
093 * Construct a new, empty HashSet whose backing HashMap has the default
094 * capacity (11) and loadFacor (0.75).
095 */
096 public HashSet()
097 {
098 this(HashMap.DEFAULT_CAPACITY, HashMap.DEFAULT_LOAD_FACTOR);
099 }
100
101 /**
102 * Construct a new, empty HashSet whose backing HashMap has the supplied
103 * capacity and the default load factor (0.75).
104 *
105 * @param initialCapacity the initial capacity of the backing HashMap
106 * @throws IllegalArgumentException if the capacity is negative
107 */
108 public HashSet(int initialCapacity)
109 {
110 this(initialCapacity, HashMap.DEFAULT_LOAD_FACTOR);
111 }
112
113 /**
114 * Construct a new, empty HashSet whose backing HashMap has the supplied
115 * capacity and load factor.
116 *
117 * @param initialCapacity the initial capacity of the backing HashMap
118 * @param loadFactor the load factor of the backing HashMap
119 * @throws IllegalArgumentException if either argument is negative, or
120 * if loadFactor is POSITIVE_INFINITY or NaN
121 */
122 public HashSet(int initialCapacity, float loadFactor)
123 {
124 map = init(initialCapacity, loadFactor);
125 }
126
127 /**
128 * Construct a new HashSet with the same elements as are in the supplied
129 * collection (eliminating any duplicates, of course). The backing storage
130 * has twice the size of the collection, or the default size of 11,
131 * whichever is greater; and the default load factor (0.75).
132 *
133 * @param c a collection of initial set elements
134 * @throws NullPointerException if c is null
135 */
136 public HashSet(Collection<? extends T> c)
137 {
138 this(Math.max(2 * c.size(), HashMap.DEFAULT_CAPACITY));
139 addAll(c);
140 }
141
142 /**
143 * Adds the given Object to the set if it is not already in the Set.
144 * This set permits a null element.
145 *
146 * @param o the Object to add to this Set
147 * @return true if the set did not already contain o
148 */
149 public boolean add(T o)
150 {
151 return map.put(o, "") == null;
152 }
153
154 /**
155 * Empties this Set of all elements; this takes constant time.
156 */
157 public void clear()
158 {
159 map.clear();
160 }
161
162 /**
163 * Returns a shallow copy of this Set. The Set itself is cloned; its
164 * elements are not.
165 *
166 * @return a shallow clone of the set
167 */
168 public Object clone()
169 {
170 HashSet<T> copy = null;
171 try
172 {
173 copy = (HashSet<T>) super.clone();
174 }
175 catch (CloneNotSupportedException x)
176 {
177 // Impossible to get here.
178 }
179 copy.map = (HashMap<T, String>) map.clone();
180 return copy;
181 }
182
183 /**
184 * Returns true if the supplied element is in this Set.
185 *
186 * @param o the Object to look for
187 * @return true if it is in the set
188 */
189 public boolean contains(Object o)
190 {
191 return map.containsKey(o);
192 }
193
194 /**
195 * Returns true if this set has no elements in it.
196 *
197 * @return <code>size() == 0</code>.
198 */
199 public boolean isEmpty()
200 {
201 return map.size == 0;
202 }
203
204 /**
205 * Returns an Iterator over the elements of this Set, which visits the
206 * elements in no particular order. For this class, the Iterator allows
207 * removal of elements. The iterator is fail-fast, and will throw a
208 * ConcurrentModificationException if the set is modified externally.
209 *
210 * @return a set iterator
211 * @see ConcurrentModificationException
212 */
213 public Iterator<T> iterator()
214 {
215 // Avoid creating intermediate keySet() object by using non-public API.
216 return map.iterator(HashMap.KEYS);
217 }
218
219 /**
220 * Removes the supplied Object from this Set if it is in the Set.
221 *
222 * @param o the object to remove
223 * @return true if an element was removed
224 */
225 public boolean remove(Object o)
226 {
227 return (map.remove(o) != null);
228 }
229
230 /**
231 * Returns the number of elements in this Set (its cardinality).
232 *
233 * @return the size of the set
234 */
235 public int size()
236 {
237 return map.size;
238 }
239
240 /**
241 * Helper method which initializes the backing Map. Overridden by
242 * LinkedHashSet for correct semantics.
243 *
244 * @param capacity the initial capacity
245 * @param load the initial load factor
246 * @return the backing HashMap
247 */
248 HashMap init(int capacity, float load)
249 {
250 return new HashMap(capacity, load);
251 }
252
253 /**
254 * Serializes this object to the given stream.
255 *
256 * @param s the stream to write to
257 * @throws IOException if the underlying stream fails
258 * @serialData the <i>capacity</i> (int) and <i>loadFactor</i> (float)
259 * of the backing store, followed by the set size (int),
260 * then a listing of its elements (Object) in no order
261 */
262 private void writeObject(ObjectOutputStream s) throws IOException
263 {
264 s.defaultWriteObject();
265 // Avoid creating intermediate keySet() object by using non-public API.
266 Iterator<T> it = map.iterator(HashMap.KEYS);
267 s.writeInt(map.buckets.length);
268 s.writeFloat(map.loadFactor);
269 s.writeInt(map.size);
270 while (it.hasNext())
271 s.writeObject(it.next());
272 }
273
274 /**
275 * Deserializes this object from the given stream.
276 *
277 * @param s the stream to read from
278 * @throws ClassNotFoundException if the underlying stream fails
279 * @throws IOException if the underlying stream fails
280 * @serialData the <i>capacity</i> (int) and <i>loadFactor</i> (float)
281 * of the backing store, followed by the set size (int),
282 * then a listing of its elements (Object) in no order
283 */
284 private void readObject(ObjectInputStream s)
285 throws IOException, ClassNotFoundException
286 {
287 s.defaultReadObject();
288
289 map = init(s.readInt(), s.readFloat());
290 for (int size = s.readInt(); size > 0; size--)
291 map.put((T) s.readObject(), "");
292 }
293 }