HashSet.java 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /* HashSet.java -- a class providing a HashMap-backed Set
  2. Copyright (C) 1998, 1999, 2001, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import java.io.IOException;
  33. import java.io.ObjectInputStream;
  34. import java.io.ObjectOutputStream;
  35. import java.io.Serializable;
  36. /**
  37. * This class provides a HashMap-backed implementation of the Set interface.
  38. * <p>
  39. *
  40. * Most operations are O(1), assuming no hash collisions. In the worst
  41. * case (where all hashes collide), operations are O(n). Setting the
  42. * initial capacity too low will force many resizing operations, but
  43. * setting the initial capacity too high (or loadfactor too low) leads
  44. * to wasted memory and slower iteration.
  45. * <p>
  46. *
  47. * HashSet accepts the null key and null values. It is not synchronized,
  48. * so if you need multi-threaded access, consider using:<br>
  49. * <code>Set s = Collections.synchronizedSet(new HashSet(...));</code>
  50. * <p>
  51. *
  52. * The iterators are <i>fail-fast</i>, meaning that any structural
  53. * modification, except for <code>remove()</code> called on the iterator
  54. * itself, cause the iterator to throw a
  55. * {@link ConcurrentModificationException} rather than exhibit
  56. * non-deterministic behavior.
  57. *
  58. * @author Jon Zeppieri
  59. * @author Eric Blake (ebb9@email.byu.edu)
  60. * @see Collection
  61. * @see Set
  62. * @see TreeSet
  63. * @see Collections#synchronizedSet(Set)
  64. * @see HashMap
  65. * @see LinkedHashSet
  66. * @since 1.2
  67. * @status updated to 1.4
  68. */
  69. public class HashSet<T> extends AbstractSet<T>
  70. implements Set<T>, Cloneable, Serializable
  71. {
  72. /**
  73. * Compatible with JDK 1.2.
  74. */
  75. private static final long serialVersionUID = -5024744406713321676L;
  76. /**
  77. * The HashMap which backs this Set.
  78. */
  79. private transient HashMap<T, String> map;
  80. /**
  81. * Construct a new, empty HashSet whose backing HashMap has the default
  82. * capacity (11) and loadFacor (0.75).
  83. */
  84. public HashSet()
  85. {
  86. this(HashMap.DEFAULT_CAPACITY, HashMap.DEFAULT_LOAD_FACTOR);
  87. }
  88. /**
  89. * Construct a new, empty HashSet whose backing HashMap has the supplied
  90. * capacity and the default load factor (0.75).
  91. *
  92. * @param initialCapacity the initial capacity of the backing HashMap
  93. * @throws IllegalArgumentException if the capacity is negative
  94. */
  95. public HashSet(int initialCapacity)
  96. {
  97. this(initialCapacity, HashMap.DEFAULT_LOAD_FACTOR);
  98. }
  99. /**
  100. * Construct a new, empty HashSet whose backing HashMap has the supplied
  101. * capacity and load factor.
  102. *
  103. * @param initialCapacity the initial capacity of the backing HashMap
  104. * @param loadFactor the load factor of the backing HashMap
  105. * @throws IllegalArgumentException if either argument is negative, or
  106. * if loadFactor is POSITIVE_INFINITY or NaN
  107. */
  108. public HashSet(int initialCapacity, float loadFactor)
  109. {
  110. map = init(initialCapacity, loadFactor);
  111. }
  112. /**
  113. * Construct a new HashSet with the same elements as are in the supplied
  114. * collection (eliminating any duplicates, of course). The backing storage
  115. * has twice the size of the collection, or the default size of 11,
  116. * whichever is greater; and the default load factor (0.75).
  117. *
  118. * @param c a collection of initial set elements
  119. * @throws NullPointerException if c is null
  120. */
  121. public HashSet(Collection<? extends T> c)
  122. {
  123. this(Math.max(2 * c.size(), HashMap.DEFAULT_CAPACITY));
  124. addAll(c);
  125. }
  126. /**
  127. * Adds the given Object to the set if it is not already in the Set.
  128. * This set permits a null element.
  129. *
  130. * @param o the Object to add to this Set
  131. * @return true if the set did not already contain o
  132. */
  133. public boolean add(T o)
  134. {
  135. return map.put(o, "") == null;
  136. }
  137. /**
  138. * Empties this Set of all elements; this takes constant time.
  139. */
  140. public void clear()
  141. {
  142. map.clear();
  143. }
  144. /**
  145. * Returns a shallow copy of this Set. The Set itself is cloned; its
  146. * elements are not.
  147. *
  148. * @return a shallow clone of the set
  149. */
  150. public Object clone()
  151. {
  152. HashSet<T> copy = null;
  153. try
  154. {
  155. copy = (HashSet<T>) super.clone();
  156. }
  157. catch (CloneNotSupportedException x)
  158. {
  159. // Impossible to get here.
  160. }
  161. copy.map = (HashMap<T, String>) map.clone();
  162. return copy;
  163. }
  164. /**
  165. * Returns true if the supplied element is in this Set.
  166. *
  167. * @param o the Object to look for
  168. * @return true if it is in the set
  169. */
  170. public boolean contains(Object o)
  171. {
  172. return map.containsKey(o);
  173. }
  174. /**
  175. * Returns true if this set has no elements in it.
  176. *
  177. * @return <code>size() == 0</code>.
  178. */
  179. public boolean isEmpty()
  180. {
  181. return map.size == 0;
  182. }
  183. /**
  184. * Returns an Iterator over the elements of this Set, which visits the
  185. * elements in no particular order. For this class, the Iterator allows
  186. * removal of elements. The iterator is fail-fast, and will throw a
  187. * ConcurrentModificationException if the set is modified externally.
  188. *
  189. * @return a set iterator
  190. * @see ConcurrentModificationException
  191. */
  192. public Iterator<T> iterator()
  193. {
  194. // Avoid creating intermediate keySet() object by using non-public API.
  195. return map.iterator(HashMap.KEYS);
  196. }
  197. /**
  198. * Removes the supplied Object from this Set if it is in the Set.
  199. *
  200. * @param o the object to remove
  201. * @return true if an element was removed
  202. */
  203. public boolean remove(Object o)
  204. {
  205. return (map.remove(o) != null);
  206. }
  207. /**
  208. * Returns the number of elements in this Set (its cardinality).
  209. *
  210. * @return the size of the set
  211. */
  212. public int size()
  213. {
  214. return map.size;
  215. }
  216. /**
  217. * Helper method which initializes the backing Map. Overridden by
  218. * LinkedHashSet for correct semantics.
  219. *
  220. * @param capacity the initial capacity
  221. * @param load the initial load factor
  222. * @return the backing HashMap
  223. */
  224. HashMap init(int capacity, float load)
  225. {
  226. return new HashMap(capacity, load);
  227. }
  228. /**
  229. * Serializes this object to the given stream.
  230. *
  231. * @param s the stream to write to
  232. * @throws IOException if the underlying stream fails
  233. * @serialData the <i>capacity</i> (int) and <i>loadFactor</i> (float)
  234. * of the backing store, followed by the set size (int),
  235. * then a listing of its elements (Object) in no order
  236. */
  237. private void writeObject(ObjectOutputStream s) throws IOException
  238. {
  239. s.defaultWriteObject();
  240. // Avoid creating intermediate keySet() object by using non-public API.
  241. Iterator<T> it = map.iterator(HashMap.KEYS);
  242. s.writeInt(map.buckets.length);
  243. s.writeFloat(map.loadFactor);
  244. s.writeInt(map.size);
  245. while (it.hasNext())
  246. s.writeObject(it.next());
  247. }
  248. /**
  249. * Deserializes this object from the given stream.
  250. *
  251. * @param s the stream to read from
  252. * @throws ClassNotFoundException if the underlying stream fails
  253. * @throws IOException if the underlying stream fails
  254. * @serialData the <i>capacity</i> (int) and <i>loadFactor</i> (float)
  255. * of the backing store, followed by the set size (int),
  256. * then a listing of its elements (Object) in no order
  257. */
  258. private void readObject(ObjectInputStream s)
  259. throws IOException, ClassNotFoundException
  260. {
  261. s.defaultReadObject();
  262. map = init(s.readInt(), s.readFloat());
  263. for (int size = s.readInt(); size > 0; size--)
  264. map.put((T) s.readObject(), "");
  265. }
  266. }