Hashtable.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. /* Hashtable.java -- a class providing a basic hashtable data structure,
  2. mapping Object --> Object
  3. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006
  4. Free Software Foundation, Inc.
  5. This file is part of GNU Classpath.
  6. GNU Classpath is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10. GNU Classpath is distributed in the hope that it will be useful, but
  11. WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with GNU Classpath; see the file COPYING. If not, write to the
  16. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  17. 02110-1301 USA.
  18. Linking this library statically or dynamically with other modules is
  19. making a combined work based on this library. Thus, the terms and
  20. conditions of the GNU General Public License cover the whole
  21. combination.
  22. As a special exception, the copyright holders of this library give you
  23. permission to link this library with independent modules to produce an
  24. executable, regardless of the license terms of these independent
  25. modules, and to copy and distribute the resulting executable under
  26. terms of your choice, provided that you also meet, for each linked
  27. independent module, the terms and conditions of the license of that
  28. module. An independent module is a module which is not derived from
  29. or based on this library. If you modify this library, you may extend
  30. this exception to your version of the library, but you are not
  31. obligated to do so. If you do not wish to do so, delete this
  32. exception statement from your version. */
  33. package java.util;
  34. import gnu.java.lang.CPStringBuilder;
  35. import java.io.IOException;
  36. import java.io.ObjectInputStream;
  37. import java.io.ObjectOutputStream;
  38. import java.io.Serializable;
  39. // NOTE: This implementation is very similar to that of HashMap. If you fix
  40. // a bug in here, chances are you should make a similar change to the HashMap
  41. // code.
  42. /**
  43. * A class which implements a hashtable data structure.
  44. * <p>
  45. *
  46. * This implementation of Hashtable uses a hash-bucket approach. That is:
  47. * linear probing and rehashing is avoided; instead, each hashed value maps
  48. * to a simple linked-list which, in the best case, only has one node.
  49. * Assuming a large enough table, low enough load factor, and / or well
  50. * implemented hashCode() methods, Hashtable should provide O(1)
  51. * insertion, deletion, and searching of keys. Hashtable is O(n) in
  52. * the worst case for all of these (if all keys hash to the same bucket).
  53. * <p>
  54. *
  55. * This is a JDK-1.2 compliant implementation of Hashtable. As such, it
  56. * belongs, partially, to the Collections framework (in that it implements
  57. * Map). For backwards compatibility, it inherits from the obsolete and
  58. * utterly useless Dictionary class.
  59. * <p>
  60. *
  61. * Being a hybrid of old and new, Hashtable has methods which provide redundant
  62. * capability, but with subtle and even crucial differences.
  63. * For example, one can iterate over various aspects of a Hashtable with
  64. * either an Iterator (which is the JDK-1.2 way of doing things) or with an
  65. * Enumeration. The latter can end up in an undefined state if the Hashtable
  66. * changes while the Enumeration is open.
  67. * <p>
  68. *
  69. * Unlike HashMap, Hashtable does not accept `null' as a key value. Also,
  70. * all accesses are synchronized: in a single thread environment, this is
  71. * expensive, but in a multi-thread environment, this saves you the effort
  72. * of extra synchronization. However, the old-style enumerators are not
  73. * synchronized, because they can lead to unspecified behavior even if
  74. * they were synchronized. You have been warned.
  75. * <p>
  76. *
  77. * The iterators are <i>fail-fast</i>, meaning that any structural
  78. * modification, except for <code>remove()</code> called on the iterator
  79. * itself, cause the iterator to throw a
  80. * <code>ConcurrentModificationException</code> rather than exhibit
  81. * non-deterministic behavior.
  82. *
  83. * @author Jon Zeppieri
  84. * @author Warren Levy
  85. * @author Bryce McKinlay
  86. * @author Eric Blake (ebb9@email.byu.edu)
  87. * @see HashMap
  88. * @see TreeMap
  89. * @see IdentityHashMap
  90. * @see LinkedHashMap
  91. * @since 1.0
  92. * @status updated to 1.4
  93. */
  94. public class Hashtable<K, V> extends Dictionary<K, V>
  95. implements Map<K, V>, Cloneable, Serializable
  96. {
  97. // WARNING: Hashtable is a CORE class in the bootstrap cycle. See the
  98. // comments in vm/reference/java/lang/Runtime for implications of this fact.
  99. /** Default number of buckets. This is the value the JDK 1.3 uses. Some
  100. * early documentation specified this value as 101. That is incorrect.
  101. */
  102. private static final int DEFAULT_CAPACITY = 11;
  103. /**
  104. * The default load factor; this is explicitly specified by the spec.
  105. */
  106. private static final float DEFAULT_LOAD_FACTOR = 0.75f;
  107. /**
  108. * Compatible with JDK 1.0+.
  109. */
  110. private static final long serialVersionUID = 1421746759512286392L;
  111. /**
  112. * The rounded product of the capacity and the load factor; when the number
  113. * of elements exceeds the threshold, the Hashtable calls
  114. * <code>rehash()</code>.
  115. * @serial
  116. */
  117. private int threshold;
  118. /**
  119. * Load factor of this Hashtable: used in computing the threshold.
  120. * @serial
  121. */
  122. private final float loadFactor;
  123. /**
  124. * Array containing the actual key-value mappings.
  125. */
  126. // Package visible for use by nested classes.
  127. transient HashEntry<K, V>[] buckets;
  128. /**
  129. * Counts the number of modifications this Hashtable has undergone, used
  130. * by Iterators to know when to throw ConcurrentModificationExceptions.
  131. */
  132. // Package visible for use by nested classes.
  133. transient int modCount;
  134. /**
  135. * The size of this Hashtable: denotes the number of key-value pairs.
  136. */
  137. // Package visible for use by nested classes.
  138. transient int size;
  139. /**
  140. * The cache for {@link #keySet()}.
  141. */
  142. private transient Set<K> keys;
  143. /**
  144. * The cache for {@link #values()}.
  145. */
  146. private transient Collection<V> values;
  147. /**
  148. * The cache for {@link #entrySet()}.
  149. */
  150. private transient Set<Map.Entry<K, V>> entries;
  151. /**
  152. * Class to represent an entry in the hash table. Holds a single key-value
  153. * pair. A Hashtable Entry is identical to a HashMap Entry, except that
  154. * `null' is not allowed for keys and values.
  155. */
  156. private static final class HashEntry<K, V>
  157. extends AbstractMap.SimpleEntry<K, V>
  158. {
  159. /** The next entry in the linked list. */
  160. HashEntry<K, V> next;
  161. /**
  162. * Simple constructor.
  163. * @param key the key, already guaranteed non-null
  164. * @param value the value, already guaranteed non-null
  165. */
  166. HashEntry(K key, V value)
  167. {
  168. super(key, value);
  169. }
  170. /**
  171. * Resets the value.
  172. * @param newVal the new value
  173. * @return the prior value
  174. * @throws NullPointerException if <code>newVal</code> is null
  175. */
  176. public V setValue(V newVal)
  177. {
  178. if (newVal == null)
  179. throw new NullPointerException();
  180. return super.setValue(newVal);
  181. }
  182. }
  183. /**
  184. * Construct a new Hashtable with the default capacity (11) and the default
  185. * load factor (0.75).
  186. */
  187. public Hashtable()
  188. {
  189. this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
  190. }
  191. /**
  192. * Construct a new Hashtable from the given Map, with initial capacity
  193. * the greater of the size of <code>m</code> or the default of 11.
  194. * <p>
  195. *
  196. * Every element in Map m will be put into this new Hashtable.
  197. *
  198. * @param m a Map whose key / value pairs will be put into
  199. * the new Hashtable. <b>NOTE: key / value pairs
  200. * are not cloned in this constructor.</b>
  201. * @throws NullPointerException if m is null, or if m contains a mapping
  202. * to or from `null'.
  203. * @since 1.2
  204. */
  205. public Hashtable(Map<? extends K, ? extends V> m)
  206. {
  207. this(Math.max(m.size() * 2, DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);
  208. putAll(m);
  209. }
  210. /**
  211. * Construct a new Hashtable with a specific inital capacity and
  212. * default load factor of 0.75.
  213. *
  214. * @param initialCapacity the initial capacity of this Hashtable (&gt;= 0)
  215. * @throws IllegalArgumentException if (initialCapacity &lt; 0)
  216. */
  217. public Hashtable(int initialCapacity)
  218. {
  219. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  220. }
  221. /**
  222. * Construct a new Hashtable with a specific initial capacity and
  223. * load factor.
  224. *
  225. * @param initialCapacity the initial capacity (&gt;= 0)
  226. * @param loadFactor the load factor (&gt; 0, not NaN)
  227. * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||
  228. * ! (loadFactor &gt; 0.0)
  229. */
  230. public Hashtable(int initialCapacity, float loadFactor)
  231. {
  232. if (initialCapacity < 0)
  233. throw new IllegalArgumentException("Illegal Capacity: "
  234. + initialCapacity);
  235. if (! (loadFactor > 0)) // check for NaN too
  236. throw new IllegalArgumentException("Illegal Load: " + loadFactor);
  237. if (initialCapacity == 0)
  238. initialCapacity = 1;
  239. buckets = (HashEntry<K, V>[]) new HashEntry[initialCapacity];
  240. this.loadFactor = loadFactor;
  241. threshold = (int) (initialCapacity * loadFactor);
  242. }
  243. /**
  244. * Returns the number of key-value mappings currently in this hashtable.
  245. * @return the size
  246. */
  247. public synchronized int size()
  248. {
  249. return size;
  250. }
  251. /**
  252. * Returns true if there are no key-value mappings currently in this table.
  253. * @return <code>size() == 0</code>
  254. */
  255. public synchronized boolean isEmpty()
  256. {
  257. return size == 0;
  258. }
  259. /**
  260. * Return an enumeration of the keys of this table. There's no point
  261. * in synchronizing this, as you have already been warned that the
  262. * enumeration is not specified to be thread-safe.
  263. *
  264. * @return the keys
  265. * @see #elements()
  266. * @see #keySet()
  267. */
  268. public Enumeration<K> keys()
  269. {
  270. return new KeyEnumerator();
  271. }
  272. /**
  273. * Return an enumeration of the values of this table. There's no point
  274. * in synchronizing this, as you have already been warned that the
  275. * enumeration is not specified to be thread-safe.
  276. *
  277. * @return the values
  278. * @see #keys()
  279. * @see #values()
  280. */
  281. public Enumeration<V> elements()
  282. {
  283. return new ValueEnumerator();
  284. }
  285. /**
  286. * Returns true if this Hashtable contains a value <code>o</code>,
  287. * such that <code>o.equals(value)</code>. This is the same as
  288. * <code>containsValue()</code>, and is O(n).
  289. * <p>
  290. *
  291. * @param value the value to search for in this Hashtable
  292. * @return true if at least one key maps to the value
  293. * @throws NullPointerException if <code>value</code> is null
  294. * @see #containsValue(Object)
  295. * @see #containsKey(Object)
  296. */
  297. public synchronized boolean contains(Object value)
  298. {
  299. if (value == null)
  300. throw new NullPointerException();
  301. for (int i = buckets.length - 1; i >= 0; i--)
  302. {
  303. HashEntry<K, V> e = buckets[i];
  304. while (e != null)
  305. {
  306. if (e.value.equals(value))
  307. return true;
  308. e = e.next;
  309. }
  310. }
  311. return false;
  312. }
  313. /**
  314. * Returns true if this Hashtable contains a value <code>o</code>, such that
  315. * <code>o.equals(value)</code>. This is the new API for the old
  316. * <code>contains()</code>.
  317. *
  318. * @param value the value to search for in this Hashtable
  319. * @return true if at least one key maps to the value
  320. * @see #contains(Object)
  321. * @see #containsKey(Object)
  322. * @throws NullPointerException if <code>value</code> is null
  323. * @since 1.2
  324. */
  325. public boolean containsValue(Object value)
  326. {
  327. // Delegate to older method to make sure code overriding it continues
  328. // to work.
  329. return contains(value);
  330. }
  331. /**
  332. * Returns true if the supplied object <code>equals()</code> a key
  333. * in this Hashtable.
  334. *
  335. * @param key the key to search for in this Hashtable
  336. * @return true if the key is in the table
  337. * @throws NullPointerException if key is null
  338. * @see #containsValue(Object)
  339. */
  340. public synchronized boolean containsKey(Object key)
  341. {
  342. int idx = hash(key);
  343. HashEntry<K, V> e = buckets[idx];
  344. while (e != null)
  345. {
  346. if (e.key.equals(key))
  347. return true;
  348. e = e.next;
  349. }
  350. return false;
  351. }
  352. /**
  353. * Return the value in this Hashtable associated with the supplied key,
  354. * or <code>null</code> if the key maps to nothing.
  355. *
  356. * @param key the key for which to fetch an associated value
  357. * @return what the key maps to, if present
  358. * @throws NullPointerException if key is null
  359. * @see #put(Object, Object)
  360. * @see #containsKey(Object)
  361. */
  362. public synchronized V get(Object key)
  363. {
  364. int idx = hash(key);
  365. HashEntry<K, V> e = buckets[idx];
  366. while (e != null)
  367. {
  368. if (e.key.equals(key))
  369. return e.value;
  370. e = e.next;
  371. }
  372. return null;
  373. }
  374. /**
  375. * Puts the supplied value into the Map, mapped by the supplied key.
  376. * Neither parameter may be null. The value may be retrieved by any
  377. * object which <code>equals()</code> this key.
  378. *
  379. * @param key the key used to locate the value
  380. * @param value the value to be stored in the table
  381. * @return the prior mapping of the key, or null if there was none
  382. * @throws NullPointerException if key or value is null
  383. * @see #get(Object)
  384. * @see Object#equals(Object)
  385. */
  386. public synchronized V put(K key, V value)
  387. {
  388. int idx = hash(key);
  389. HashEntry<K, V> e = buckets[idx];
  390. // Check if value is null since it is not permitted.
  391. if (value == null)
  392. throw new NullPointerException();
  393. while (e != null)
  394. {
  395. if (e.key.equals(key))
  396. {
  397. // Bypass e.setValue, since we already know value is non-null.
  398. V r = e.value;
  399. e.value = value;
  400. return r;
  401. }
  402. else
  403. {
  404. e = e.next;
  405. }
  406. }
  407. // At this point, we know we need to add a new entry.
  408. modCount++;
  409. if (++size > threshold)
  410. {
  411. rehash();
  412. // Need a new hash value to suit the bigger table.
  413. idx = hash(key);
  414. }
  415. e = new HashEntry<K, V>(key, value);
  416. e.next = buckets[idx];
  417. buckets[idx] = e;
  418. return null;
  419. }
  420. /**
  421. * Removes from the table and returns the value which is mapped by the
  422. * supplied key. If the key maps to nothing, then the table remains
  423. * unchanged, and <code>null</code> is returned.
  424. *
  425. * @param key the key used to locate the value to remove
  426. * @return whatever the key mapped to, if present
  427. */
  428. public synchronized V remove(Object key)
  429. {
  430. int idx = hash(key);
  431. HashEntry<K, V> e = buckets[idx];
  432. HashEntry<K, V> last = null;
  433. while (e != null)
  434. {
  435. if (e.key.equals(key))
  436. {
  437. modCount++;
  438. if (last == null)
  439. buckets[idx] = e.next;
  440. else
  441. last.next = e.next;
  442. size--;
  443. return e.value;
  444. }
  445. last = e;
  446. e = e.next;
  447. }
  448. return null;
  449. }
  450. /**
  451. * Copies all elements of the given map into this hashtable. However, no
  452. * mapping can contain null as key or value. If this table already has
  453. * a mapping for a key, the new mapping replaces the current one.
  454. *
  455. * @param m the map to be hashed into this
  456. * @throws NullPointerException if m is null, or contains null keys or values
  457. */
  458. public synchronized void putAll(Map<? extends K, ? extends V> m)
  459. {
  460. final Map<K,V> addMap = (Map<K,V>) m;
  461. final Iterator<Map.Entry<K,V>> it = addMap.entrySet().iterator();
  462. while (it.hasNext())
  463. {
  464. final Map.Entry<K,V> e = it.next();
  465. // Optimize in case the Entry is one of our own.
  466. if (e instanceof AbstractMap.SimpleEntry)
  467. {
  468. AbstractMap.SimpleEntry<? extends K, ? extends V> entry
  469. = (AbstractMap.SimpleEntry<? extends K, ? extends V>) e;
  470. put(entry.key, entry.value);
  471. }
  472. else
  473. {
  474. put(e.getKey(), e.getValue());
  475. }
  476. }
  477. }
  478. /**
  479. * Clears the hashtable so it has no keys. This is O(1).
  480. */
  481. public synchronized void clear()
  482. {
  483. if (size > 0)
  484. {
  485. modCount++;
  486. Arrays.fill(buckets, null);
  487. size = 0;
  488. }
  489. }
  490. /**
  491. * Returns a shallow clone of this Hashtable. The Map itself is cloned,
  492. * but its contents are not. This is O(n).
  493. *
  494. * @return the clone
  495. */
  496. public synchronized Object clone()
  497. {
  498. Hashtable<K, V> copy = null;
  499. try
  500. {
  501. copy = (Hashtable<K, V>) super.clone();
  502. }
  503. catch (CloneNotSupportedException x)
  504. {
  505. // This is impossible.
  506. }
  507. copy.buckets = (HashEntry<K, V>[]) new HashEntry[buckets.length];
  508. copy.putAllInternal(this);
  509. // Clear the caches.
  510. copy.keys = null;
  511. copy.values = null;
  512. copy.entries = null;
  513. return copy;
  514. }
  515. /**
  516. * Converts this Hashtable to a String, surrounded by braces, and with
  517. * key/value pairs listed with an equals sign between, separated by a
  518. * comma and space. For example, <code>"{a=1, b=2}"</code>.<p>
  519. *
  520. * NOTE: if the <code>toString()</code> method of any key or value
  521. * throws an exception, this will fail for the same reason.
  522. *
  523. * @return the string representation
  524. */
  525. public synchronized String toString()
  526. {
  527. // Since we are already synchronized, and entrySet().iterator()
  528. // would repeatedly re-lock/release the monitor, we directly use the
  529. // unsynchronized EntryIterator instead.
  530. Iterator<Map.Entry<K, V>> entries = new EntryIterator();
  531. CPStringBuilder r = new CPStringBuilder("{");
  532. for (int pos = size; pos > 0; pos--)
  533. {
  534. r.append(entries.next());
  535. if (pos > 1)
  536. r.append(", ");
  537. }
  538. r.append("}");
  539. return r.toString();
  540. }
  541. /**
  542. * Returns a "set view" of this Hashtable's keys. The set is backed by
  543. * the hashtable, so changes in one show up in the other. The set supports
  544. * element removal, but not element addition. The set is properly
  545. * synchronized on the original hashtable. Sun has not documented the
  546. * proper interaction of null with this set, but has inconsistent behavior
  547. * in the JDK. Therefore, in this implementation, contains, remove,
  548. * containsAll, retainAll, removeAll, and equals just ignore a null key
  549. * rather than throwing a {@link NullPointerException}.
  550. *
  551. * @return a set view of the keys
  552. * @see #values()
  553. * @see #entrySet()
  554. * @since 1.2
  555. */
  556. public Set<K> keySet()
  557. {
  558. if (keys == null)
  559. {
  560. // Create a synchronized AbstractSet with custom implementations of
  561. // those methods that can be overridden easily and efficiently.
  562. Set<K> r = new AbstractSet<K>()
  563. {
  564. public int size()
  565. {
  566. return size;
  567. }
  568. public Iterator<K> iterator()
  569. {
  570. return new KeyIterator();
  571. }
  572. public void clear()
  573. {
  574. Hashtable.this.clear();
  575. }
  576. public boolean contains(Object o)
  577. {
  578. if (o == null)
  579. return false;
  580. return containsKey(o);
  581. }
  582. public boolean remove(Object o)
  583. {
  584. return Hashtable.this.remove(o) != null;
  585. }
  586. };
  587. // We must specify the correct object to synchronize upon, hence the
  588. // use of a non-public API
  589. keys = new Collections.SynchronizedSet<K>(this, r);
  590. }
  591. return keys;
  592. }
  593. /**
  594. * Returns a "collection view" (or "bag view") of this Hashtable's values.
  595. * The collection is backed by the hashtable, so changes in one show up
  596. * in the other. The collection supports element removal, but not element
  597. * addition. The collection is properly synchronized on the original
  598. * hashtable. Sun has not documented the proper interaction of null with
  599. * this set, but has inconsistent behavior in the JDK. Therefore, in this
  600. * implementation, contains, remove, containsAll, retainAll, removeAll, and
  601. * equals just ignore a null value rather than throwing a
  602. * {@link NullPointerException}.
  603. *
  604. * @return a bag view of the values
  605. * @see #keySet()
  606. * @see #entrySet()
  607. * @since 1.2
  608. */
  609. public Collection<V> values()
  610. {
  611. if (values == null)
  612. {
  613. // We don't bother overriding many of the optional methods, as doing so
  614. // wouldn't provide any significant performance advantage.
  615. Collection<V> r = new AbstractCollection<V>()
  616. {
  617. public int size()
  618. {
  619. return size;
  620. }
  621. public Iterator<V> iterator()
  622. {
  623. return new ValueIterator();
  624. }
  625. public void clear()
  626. {
  627. Hashtable.this.clear();
  628. }
  629. };
  630. // We must specify the correct object to synchronize upon, hence the
  631. // use of a non-public API
  632. values = new Collections.SynchronizedCollection<V>(this, r);
  633. }
  634. return values;
  635. }
  636. /**
  637. * Returns a "set view" of this Hashtable's entries. The set is backed by
  638. * the hashtable, so changes in one show up in the other. The set supports
  639. * element removal, but not element addition. The set is properly
  640. * synchronized on the original hashtable. Sun has not documented the
  641. * proper interaction of null with this set, but has inconsistent behavior
  642. * in the JDK. Therefore, in this implementation, contains, remove,
  643. * containsAll, retainAll, removeAll, and equals just ignore a null entry,
  644. * or an entry with a null key or value, rather than throwing a
  645. * {@link NullPointerException}. However, calling entry.setValue(null)
  646. * will fail.
  647. * <p>
  648. *
  649. * Note that the iterators for all three views, from keySet(), entrySet(),
  650. * and values(), traverse the hashtable in the same sequence.
  651. *
  652. * @return a set view of the entries
  653. * @see #keySet()
  654. * @see #values()
  655. * @see Map.Entry
  656. * @since 1.2
  657. */
  658. public Set<Map.Entry<K, V>> entrySet()
  659. {
  660. if (entries == null)
  661. {
  662. // Create an AbstractSet with custom implementations of those methods
  663. // that can be overridden easily and efficiently.
  664. Set<Map.Entry<K, V>> r = new AbstractSet<Map.Entry<K, V>>()
  665. {
  666. public int size()
  667. {
  668. return size;
  669. }
  670. public Iterator<Map.Entry<K, V>> iterator()
  671. {
  672. return new EntryIterator();
  673. }
  674. public void clear()
  675. {
  676. Hashtable.this.clear();
  677. }
  678. public boolean contains(Object o)
  679. {
  680. return getEntry(o) != null;
  681. }
  682. public boolean remove(Object o)
  683. {
  684. HashEntry<K, V> e = getEntry(o);
  685. if (e != null)
  686. {
  687. Hashtable.this.remove(e.key);
  688. return true;
  689. }
  690. return false;
  691. }
  692. };
  693. // We must specify the correct object to synchronize upon, hence the
  694. // use of a non-public API
  695. entries = new Collections.SynchronizedSet<Map.Entry<K, V>>(this, r);
  696. }
  697. return entries;
  698. }
  699. /**
  700. * Returns true if this Hashtable equals the supplied Object <code>o</code>.
  701. * As specified by Map, this is:
  702. * <code>
  703. * (o instanceof Map) && entrySet().equals(((Map) o).entrySet());
  704. * </code>
  705. *
  706. * @param o the object to compare to
  707. * @return true if o is an equal map
  708. * @since 1.2
  709. */
  710. public boolean equals(Object o)
  711. {
  712. // no need to synchronize, entrySet().equals() does that.
  713. if (o == this)
  714. return true;
  715. if (!(o instanceof Map))
  716. return false;
  717. return entrySet().equals(((Map) o).entrySet());
  718. }
  719. /**
  720. * Returns the hashCode for this Hashtable. As specified by Map, this is
  721. * the sum of the hashCodes of all of its Map.Entry objects
  722. *
  723. * @return the sum of the hashcodes of the entries
  724. * @since 1.2
  725. */
  726. public synchronized int hashCode()
  727. {
  728. // Since we are already synchronized, and entrySet().iterator()
  729. // would repeatedly re-lock/release the monitor, we directly use the
  730. // unsynchronized EntryIterator instead.
  731. Iterator<Map.Entry<K, V>> itr = new EntryIterator();
  732. int hashcode = 0;
  733. for (int pos = size; pos > 0; pos--)
  734. hashcode += itr.next().hashCode();
  735. return hashcode;
  736. }
  737. /**
  738. * Helper method that returns an index in the buckets array for `key'
  739. * based on its hashCode().
  740. *
  741. * @param key the key
  742. * @return the bucket number
  743. * @throws NullPointerException if key is null
  744. */
  745. private int hash(Object key)
  746. {
  747. // Note: Inline Math.abs here, for less method overhead, and to avoid
  748. // a bootstrap dependency, since Math relies on native methods.
  749. int hash = key.hashCode() % buckets.length;
  750. return hash < 0 ? -hash : hash;
  751. }
  752. /**
  753. * Helper method for entrySet(), which matches both key and value
  754. * simultaneously. Ignores null, as mentioned in entrySet().
  755. *
  756. * @param o the entry to match
  757. * @return the matching entry, if found, or null
  758. * @see #entrySet()
  759. */
  760. // Package visible, for use in nested classes.
  761. HashEntry<K, V> getEntry(Object o)
  762. {
  763. if (! (o instanceof Map.Entry))
  764. return null;
  765. K key = ((Map.Entry<K, V>) o).getKey();
  766. if (key == null)
  767. return null;
  768. int idx = hash(key);
  769. HashEntry<K, V> e = buckets[idx];
  770. while (e != null)
  771. {
  772. if (e.equals(o))
  773. return e;
  774. e = e.next;
  775. }
  776. return null;
  777. }
  778. /**
  779. * A simplified, more efficient internal implementation of putAll(). clone()
  780. * should not call putAll or put, in order to be compatible with the JDK
  781. * implementation with respect to subclasses.
  782. *
  783. * @param m the map to initialize this from
  784. */
  785. void putAllInternal(Map<? extends K, ? extends V> m)
  786. {
  787. final Map<K,V> addMap = (Map<K,V>) m;
  788. final Iterator<Map.Entry<K,V>> it = addMap.entrySet().iterator();
  789. size = 0;
  790. while (it.hasNext())
  791. {
  792. final Map.Entry<K,V> e = it.next();
  793. size++;
  794. K key = e.getKey();
  795. int idx = hash(key);
  796. HashEntry<K, V> he = new HashEntry<K, V>(key, e.getValue());
  797. he.next = buckets[idx];
  798. buckets[idx] = he;
  799. }
  800. }
  801. /**
  802. * Increases the size of the Hashtable and rehashes all keys to new array
  803. * indices; this is called when the addition of a new value would cause
  804. * size() &gt; threshold. Note that the existing Entry objects are reused in
  805. * the new hash table.
  806. * <p>
  807. *
  808. * This is not specified, but the new size is twice the current size plus
  809. * one; this number is not always prime, unfortunately. This implementation
  810. * is not synchronized, as it is only invoked from synchronized methods.
  811. */
  812. protected void rehash()
  813. {
  814. HashEntry<K, V>[] oldBuckets = buckets;
  815. int newcapacity = (buckets.length * 2) + 1;
  816. threshold = (int) (newcapacity * loadFactor);
  817. buckets = (HashEntry<K, V>[]) new HashEntry[newcapacity];
  818. for (int i = oldBuckets.length - 1; i >= 0; i--)
  819. {
  820. HashEntry<K, V> e = oldBuckets[i];
  821. while (e != null)
  822. {
  823. int idx = hash(e.key);
  824. HashEntry<K, V> dest = buckets[idx];
  825. if (dest != null)
  826. {
  827. HashEntry next = dest.next;
  828. while (next != null)
  829. {
  830. dest = next;
  831. next = dest.next;
  832. }
  833. dest.next = e;
  834. }
  835. else
  836. {
  837. buckets[idx] = e;
  838. }
  839. HashEntry<K, V> next = e.next;
  840. e.next = null;
  841. e = next;
  842. }
  843. }
  844. }
  845. /**
  846. * Serializes this object to the given stream.
  847. *
  848. * @param s the stream to write to
  849. * @throws IOException if the underlying stream fails
  850. * @serialData the <i>capacity</i> (int) that is the length of the
  851. * bucket array, the <i>size</i> (int) of the hash map
  852. * are emitted first. They are followed by size entries,
  853. * each consisting of a key (Object) and a value (Object).
  854. */
  855. private synchronized void writeObject(ObjectOutputStream s)
  856. throws IOException
  857. {
  858. // Write the threshold and loadFactor fields.
  859. s.defaultWriteObject();
  860. s.writeInt(buckets.length);
  861. s.writeInt(size);
  862. // Since we are already synchronized, and entrySet().iterator()
  863. // would repeatedly re-lock/release the monitor, we directly use the
  864. // unsynchronized EntryIterator instead.
  865. Iterator<Map.Entry<K, V>> it = new EntryIterator();
  866. while (it.hasNext())
  867. {
  868. HashEntry<K, V> entry = (HashEntry<K, V>) it.next();
  869. s.writeObject(entry.key);
  870. s.writeObject(entry.value);
  871. }
  872. }
  873. /**
  874. * Deserializes this object from the given stream.
  875. *
  876. * @param s the stream to read from
  877. * @throws ClassNotFoundException if the underlying stream fails
  878. * @throws IOException if the underlying stream fails
  879. * @serialData the <i>capacity</i> (int) that is the length of the
  880. * bucket array, the <i>size</i> (int) of the hash map
  881. * are emitted first. They are followed by size entries,
  882. * each consisting of a key (Object) and a value (Object).
  883. */
  884. private void readObject(ObjectInputStream s)
  885. throws IOException, ClassNotFoundException
  886. {
  887. // Read the threshold and loadFactor fields.
  888. s.defaultReadObject();
  889. // Read and use capacity.
  890. buckets = (HashEntry<K, V>[]) new HashEntry[s.readInt()];
  891. int len = s.readInt();
  892. // Read and use key/value pairs.
  893. // TODO: should we be defensive programmers, and check for illegal nulls?
  894. while (--len >= 0)
  895. put((K) s.readObject(), (V) s.readObject());
  896. }
  897. /**
  898. * A class which implements the Iterator interface and is used for
  899. * iterating over Hashtables.
  900. * This implementation iterates entries. Subclasses are used to
  901. * iterate key and values. It also allows the removal of elements,
  902. * as per the Javasoft spec. Note that it is not synchronized; this
  903. * is a performance enhancer since it is never exposed externally
  904. * and is only used within synchronized blocks above.
  905. *
  906. * @author Jon Zeppieri
  907. * @author Fridjof Siebert
  908. */
  909. private class EntryIterator
  910. implements Iterator<Entry<K,V>>
  911. {
  912. /**
  913. * The number of modifications to the backing Hashtable that we know about.
  914. */
  915. int knownMod = modCount;
  916. /** The number of elements remaining to be returned by next(). */
  917. int count = size;
  918. /** Current index in the physical hash table. */
  919. int idx = buckets.length;
  920. /** The last Entry returned by a next() call. */
  921. HashEntry<K, V> last;
  922. /**
  923. * The next entry that should be returned by next(). It is set to something
  924. * if we're iterating through a bucket that contains multiple linked
  925. * entries. It is null if next() needs to find a new bucket.
  926. */
  927. HashEntry<K, V> next;
  928. /**
  929. * Construct a new EntryIterator
  930. */
  931. EntryIterator()
  932. {
  933. }
  934. /**
  935. * Returns true if the Iterator has more elements.
  936. * @return true if there are more elements
  937. */
  938. public boolean hasNext()
  939. {
  940. return count > 0;
  941. }
  942. /**
  943. * Returns the next element in the Iterator's sequential view.
  944. * @return the next element
  945. * @throws ConcurrentModificationException if the hashtable was modified
  946. * @throws NoSuchElementException if there is none
  947. */
  948. public Map.Entry<K,V> next()
  949. {
  950. if (knownMod != modCount)
  951. throw new ConcurrentModificationException();
  952. if (count == 0)
  953. throw new NoSuchElementException();
  954. count--;
  955. HashEntry<K, V> e = next;
  956. while (e == null)
  957. if (idx <= 0)
  958. return null;
  959. else
  960. e = buckets[--idx];
  961. next = e.next;
  962. last = e;
  963. return e;
  964. }
  965. /**
  966. * Removes from the backing Hashtable the last element which was fetched
  967. * with the <code>next()</code> method.
  968. * @throws ConcurrentModificationException if the hashtable was modified
  969. * @throws IllegalStateException if called when there is no last element
  970. */
  971. public void remove()
  972. {
  973. if (knownMod != modCount)
  974. throw new ConcurrentModificationException();
  975. if (last == null)
  976. throw new IllegalStateException();
  977. Hashtable.this.remove(last.key);
  978. last = null;
  979. knownMod++;
  980. }
  981. } // class EntryIterator
  982. /**
  983. * A class which implements the Iterator interface and is used for
  984. * iterating over keys in Hashtables. This class uses an
  985. * <code>EntryIterator</code> to obtain the keys of each entry.
  986. *
  987. * @author Fridtjof Siebert
  988. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  989. */
  990. private class KeyIterator
  991. implements Iterator<K>
  992. {
  993. /**
  994. * This entry iterator is used for most operations. Only
  995. * <code>next()</code> gives a different result, by returning just
  996. * the key rather than the whole element.
  997. */
  998. private final EntryIterator iterator;
  999. /**
  1000. * Construct a new KeyIterator
  1001. */
  1002. KeyIterator()
  1003. {
  1004. iterator = new EntryIterator();
  1005. }
  1006. /**
  1007. * Returns true if the entry iterator has more elements.
  1008. *
  1009. * @return true if there are more elements
  1010. * @throws ConcurrentModificationException if the hashtable was modified
  1011. */
  1012. public boolean hasNext()
  1013. {
  1014. return iterator.hasNext();
  1015. }
  1016. /**
  1017. * Returns the next element in the Iterator's sequential view.
  1018. *
  1019. * @return the next element
  1020. *
  1021. * @throws ConcurrentModificationException if the hashtable was modified
  1022. * @throws NoSuchElementException if there is none
  1023. */
  1024. public K next()
  1025. {
  1026. return ((HashEntry<K,V>) iterator.next()).key;
  1027. }
  1028. /**
  1029. * Removes the last element used by the <code>next()</code> method
  1030. * using the entry iterator.
  1031. *
  1032. * @throws ConcurrentModificationException if the hashtable was modified
  1033. * @throws IllegalStateException if called when there is no last element
  1034. */
  1035. public void remove()
  1036. {
  1037. iterator.remove();
  1038. }
  1039. } // class KeyIterator
  1040. /**
  1041. * A class which implements the Iterator interface and is used for
  1042. * iterating over values in Hashtables. This class uses an
  1043. * <code>EntryIterator</code> to obtain the values of each entry.
  1044. *
  1045. * @author Fridtjof Siebert
  1046. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  1047. */
  1048. private class ValueIterator
  1049. implements Iterator<V>
  1050. {
  1051. /**
  1052. * This entry iterator is used for most operations. Only
  1053. * <code>next()</code> gives a different result, by returning just
  1054. * the value rather than the whole element.
  1055. */
  1056. private final EntryIterator iterator;
  1057. /**
  1058. * Construct a new KeyIterator
  1059. */
  1060. ValueIterator()
  1061. {
  1062. iterator = new EntryIterator();
  1063. }
  1064. /**
  1065. * Returns true if the entry iterator has more elements.
  1066. *
  1067. * @return true if there are more elements
  1068. * @throws ConcurrentModificationException if the hashtable was modified
  1069. */
  1070. public boolean hasNext()
  1071. {
  1072. return iterator.hasNext();
  1073. }
  1074. /**
  1075. * Returns the value of the next element in the iterator's sequential view.
  1076. *
  1077. * @return the next value
  1078. *
  1079. * @throws ConcurrentModificationException if the hashtable was modified
  1080. * @throws NoSuchElementException if there is none
  1081. */
  1082. public V next()
  1083. {
  1084. return ((HashEntry<K,V>) iterator.next()).value;
  1085. }
  1086. /**
  1087. * Removes the last element used by the <code>next()</code> method
  1088. * using the entry iterator.
  1089. *
  1090. * @throws ConcurrentModificationException if the hashtable was modified
  1091. * @throws IllegalStateException if called when there is no last element
  1092. */
  1093. public void remove()
  1094. {
  1095. iterator.remove();
  1096. }
  1097. } // class ValueIterator
  1098. /**
  1099. * Enumeration view of the entries in this Hashtable, providing
  1100. * sequential access to its elements.
  1101. *
  1102. * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table
  1103. * as this could cause a rehash and we'd completely lose our place. Even
  1104. * without a rehash, it is undetermined if a new element added would
  1105. * appear in the enumeration. The spec says nothing about this, but
  1106. * the "Java Class Libraries" book implies that modifications to the
  1107. * hashtable during enumeration causes indeterminate results. Don't do it!
  1108. *
  1109. * @author Jon Zeppieri
  1110. * @author Fridjof Siebert
  1111. */
  1112. private class EntryEnumerator
  1113. implements Enumeration<Entry<K,V>>
  1114. {
  1115. /** The number of elements remaining to be returned by next(). */
  1116. int count = size;
  1117. /** Current index in the physical hash table. */
  1118. int idx = buckets.length;
  1119. /**
  1120. * Entry which will be returned by the next nextElement() call. It is
  1121. * set if we are iterating through a bucket with multiple entries, or null
  1122. * if we must look in the next bucket.
  1123. */
  1124. HashEntry<K, V> next;
  1125. /**
  1126. * Construct the enumeration.
  1127. */
  1128. EntryEnumerator()
  1129. {
  1130. // Nothing to do here.
  1131. }
  1132. /**
  1133. * Checks whether more elements remain in the enumeration.
  1134. * @return true if nextElement() will not fail.
  1135. */
  1136. public boolean hasMoreElements()
  1137. {
  1138. return count > 0;
  1139. }
  1140. /**
  1141. * Returns the next element.
  1142. * @return the next element
  1143. * @throws NoSuchElementException if there is none.
  1144. */
  1145. public Map.Entry<K,V> nextElement()
  1146. {
  1147. if (count == 0)
  1148. throw new NoSuchElementException("Hashtable Enumerator");
  1149. count--;
  1150. HashEntry<K, V> e = next;
  1151. while (e == null)
  1152. if (idx <= 0)
  1153. return null;
  1154. else
  1155. e = buckets[--idx];
  1156. next = e.next;
  1157. return e;
  1158. }
  1159. } // class EntryEnumerator
  1160. /**
  1161. * Enumeration view of this Hashtable, providing sequential access to its
  1162. * elements.
  1163. *
  1164. * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table
  1165. * as this could cause a rehash and we'd completely lose our place. Even
  1166. * without a rehash, it is undetermined if a new element added would
  1167. * appear in the enumeration. The spec says nothing about this, but
  1168. * the "Java Class Libraries" book implies that modifications to the
  1169. * hashtable during enumeration causes indeterminate results. Don't do it!
  1170. *
  1171. * @author Jon Zeppieri
  1172. * @author Fridjof Siebert
  1173. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  1174. */
  1175. private final class KeyEnumerator
  1176. implements Enumeration<K>
  1177. {
  1178. /**
  1179. * This entry enumerator is used for most operations. Only
  1180. * <code>nextElement()</code> gives a different result, by returning just
  1181. * the key rather than the whole element.
  1182. */
  1183. private final EntryEnumerator enumerator;
  1184. /**
  1185. * Construct a new KeyEnumerator
  1186. */
  1187. KeyEnumerator()
  1188. {
  1189. enumerator = new EntryEnumerator();
  1190. }
  1191. /**
  1192. * Returns true if the entry enumerator has more elements.
  1193. *
  1194. * @return true if there are more elements
  1195. * @throws ConcurrentModificationException if the hashtable was modified
  1196. */
  1197. public boolean hasMoreElements()
  1198. {
  1199. return enumerator.hasMoreElements();
  1200. }
  1201. /**
  1202. * Returns the next element.
  1203. * @return the next element
  1204. * @throws NoSuchElementException if there is none.
  1205. */
  1206. public K nextElement()
  1207. {
  1208. HashEntry<K,V> entry = (HashEntry<K,V>) enumerator.nextElement();
  1209. K retVal = null;
  1210. if (entry != null)
  1211. retVal = entry.key;
  1212. return retVal;
  1213. }
  1214. } // class KeyEnumerator
  1215. /**
  1216. * Enumeration view of this Hashtable, providing sequential access to its
  1217. * values.
  1218. *
  1219. * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table
  1220. * as this could cause a rehash and we'd completely lose our place. Even
  1221. * without a rehash, it is undetermined if a new element added would
  1222. * appear in the enumeration. The spec says nothing about this, but
  1223. * the "Java Class Libraries" book implies that modifications to the
  1224. * hashtable during enumeration causes indeterminate results. Don't do it!
  1225. *
  1226. * @author Jon Zeppieri
  1227. * @author Fridjof Siebert
  1228. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  1229. */
  1230. private final class ValueEnumerator
  1231. implements Enumeration<V>
  1232. {
  1233. /**
  1234. * This entry enumerator is used for most operations. Only
  1235. * <code>nextElement()</code> gives a different result, by returning just
  1236. * the value rather than the whole element.
  1237. */
  1238. private final EntryEnumerator enumerator;
  1239. /**
  1240. * Construct a new ValueEnumerator
  1241. */
  1242. ValueEnumerator()
  1243. {
  1244. enumerator = new EntryEnumerator();
  1245. }
  1246. /**
  1247. * Returns true if the entry enumerator has more elements.
  1248. *
  1249. * @return true if there are more elements
  1250. * @throws ConcurrentModificationException if the hashtable was modified
  1251. */
  1252. public boolean hasMoreElements()
  1253. {
  1254. return enumerator.hasMoreElements();
  1255. }
  1256. /**
  1257. * Returns the next element.
  1258. * @return the next element
  1259. * @throws NoSuchElementException if there is none.
  1260. */
  1261. public V nextElement()
  1262. {
  1263. HashEntry<K,V> entry = (HashEntry<K,V>) enumerator.nextElement();
  1264. V retVal = null;
  1265. if (entry != null)
  1266. retVal = entry.value;
  1267. return retVal;
  1268. }
  1269. } // class ValueEnumerator
  1270. } // class Hashtable