78b6d7c6c131c8b791f6ba618a52a62e69b3b01a.svn-base 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. package com.sinosoft.cm.common;
  2. import java.io.IOException;
  3. import java.io.InvalidObjectException;
  4. import java.io.Serializable;
  5. import java.util.AbstractCollection;
  6. import com.sinosoft.cm.common.AbstractMap;
  7. import java.util.AbstractSet;
  8. import java.util.Arrays;
  9. import java.util.Collection;
  10. import java.util.ConcurrentModificationException;
  11. import java.util.HashMap;
  12. import java.util.Iterator;
  13. import java.util.Map;
  14. import java.util.NoSuchElementException;
  15. import java.util.Objects;
  16. import java.util.Set;
  17. public class JsonHashMap<K,V>
  18. extends AbstractMap<K,V>
  19. implements Map<K,V>, Cloneable, Serializable
  20. {
  21. /**
  22. * The default initial capacity - MUST be a power of two.
  23. */
  24. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  25. /**
  26. * The maximum capacity, used if a higher value is implicitly specified
  27. * by either of the constructors with arguments.
  28. * MUST be a power of two <= 1<<30.
  29. */
  30. static final int MAXIMUM_CAPACITY = 1 << 30;
  31. /**
  32. * The load factor used when none specified in constructor.
  33. */
  34. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  35. /**
  36. * An empty table instance to share when the table is not inflated.
  37. */
  38. static final Entry<?,?>[] EMPTY_TABLE = {};
  39. /**
  40. * The table, resized as necessary. Length MUST Always be a power of two.
  41. */
  42. transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
  43. /**
  44. * The number of key-value mappings contained in this map.
  45. */
  46. transient int size;
  47. /**
  48. * The next size value at which to resize (capacity * load factor).
  49. * @serial
  50. */
  51. // If table == EMPTY_TABLE then this is the initial capacity at which the
  52. // table will be created when inflated.
  53. int threshold;
  54. /**
  55. * The load factor for the hash table.
  56. *
  57. * @serial
  58. */
  59. final float loadFactor;
  60. /**
  61. * The number of times this HashMap has been structurally modified
  62. * Structural modifications are those that change the number of mappings in
  63. * the HashMap or otherwise modify its internal structure (e.g.,
  64. * rehash). This field is used to make iterators on Collection-views of
  65. * the HashMap fail-fast. (See ConcurrentModificationException).
  66. */
  67. transient int modCount;
  68. /**
  69. * The default threshold of map capacity above which alternative hashing is
  70. * used for String keys. Alternative hashing reduces the incidence of
  71. * collisions due to weak hash code calculation for String keys.
  72. * <p/>
  73. * This value may be overridden by defining the system property
  74. * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
  75. * forces alternative hashing to be used at all times whereas
  76. * {@code -1} value ensures that alternative hashing is never used.
  77. */
  78. static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
  79. /**
  80. * holds values which can't be initialized until after VM is booted.
  81. */
  82. private static class Holder {
  83. /**
  84. * Table capacity above which to switch to use alternative hashing.
  85. */
  86. static final int ALTERNATIVE_HASHING_THRESHOLD;
  87. static {
  88. String altThreshold = java.security.AccessController.doPrivileged(
  89. new sun.security.action.GetPropertyAction(
  90. "jdk.map.althashing.threshold"));
  91. int threshold;
  92. try {
  93. threshold = (null != altThreshold)
  94. ? Integer.parseInt(altThreshold)
  95. : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
  96. // disable alternative hashing if -1
  97. if (threshold == -1) {
  98. threshold = Integer.MAX_VALUE;
  99. }
  100. if (threshold < 0) {
  101. throw new IllegalArgumentException("value must be positive integer.");
  102. }
  103. } catch(IllegalArgumentException failed) {
  104. throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
  105. }
  106. ALTERNATIVE_HASHING_THRESHOLD = threshold;
  107. }
  108. }
  109. /**
  110. * A randomizing value associated with this instance that is applied to
  111. * hash code of keys to make hash collisions harder to find. If 0 then
  112. * alternative hashing is disabled.
  113. */
  114. transient int hashSeed = 0;
  115. /**
  116. * Constructs an empty <tt>HashMap</tt> with the specified initial
  117. * capacity and load factor.
  118. *
  119. * @param initialCapacity the initial capacity
  120. * @param loadFactor the load factor
  121. * @throws IllegalArgumentException if the initial capacity is negative
  122. * or the load factor is nonpositive
  123. */
  124. public JsonHashMap(int initialCapacity, float loadFactor) {
  125. if (initialCapacity < 0)
  126. throw new IllegalArgumentException("Illegal initial capacity: " +
  127. initialCapacity);
  128. if (initialCapacity > MAXIMUM_CAPACITY)
  129. initialCapacity = MAXIMUM_CAPACITY;
  130. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  131. throw new IllegalArgumentException("Illegal load factor: " +
  132. loadFactor);
  133. this.loadFactor = loadFactor;
  134. threshold = initialCapacity;
  135. init();
  136. }
  137. /**
  138. * Constructs an empty <tt>HashMap</tt> with the specified initial
  139. * capacity and the default load factor (0.75).
  140. *
  141. * @param initialCapacity the initial capacity.
  142. * @throws IllegalArgumentException if the initial capacity is negative.
  143. */
  144. public JsonHashMap(int initialCapacity) {
  145. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  146. }
  147. /**
  148. * Constructs an empty <tt>HashMap</tt> with the default initial capacity
  149. * (16) and the default load factor (0.75).
  150. */
  151. public JsonHashMap() {
  152. this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
  153. }
  154. /**
  155. * Constructs a new <tt>HashMap</tt> with the same mappings as the
  156. * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
  157. * default load factor (0.75) and an initial capacity sufficient to
  158. * hold the mappings in the specified <tt>Map</tt>.
  159. *
  160. * @param m the map whose mappings are to be placed in this map
  161. * @throws NullPointerException if the specified map is null
  162. */
  163. public JsonHashMap(Map<? extends K, ? extends V> m) {
  164. this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
  165. DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
  166. inflateTable(threshold);
  167. putAllForCreate(m);
  168. }
  169. private static int roundUpToPowerOf2(int number) {
  170. // assert number >= 0 : "number must be non-negative";
  171. int rounded = number >= MAXIMUM_CAPACITY
  172. ? MAXIMUM_CAPACITY
  173. : (rounded = Integer.highestOneBit(number)) != 0
  174. ? (Integer.bitCount(number) > 1) ? rounded << 1 : rounded
  175. : 1;
  176. return rounded;
  177. }
  178. /**
  179. * Inflates the table.
  180. */
  181. private void inflateTable(int toSize) {
  182. // Find a power of 2 >= toSize
  183. int capacity = roundUpToPowerOf2(toSize);
  184. threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
  185. table = new Entry[capacity];
  186. initHashSeedAsNeeded(capacity);
  187. }
  188. // internal utilities
  189. /**
  190. * Initialization hook for subclasses. This method is called
  191. * in all constructors and pseudo-constructors (clone, readObject)
  192. * after HashMap has been initialized but before any entries have
  193. * been inserted. (In the absence of this method, readObject would
  194. * require explicit knowledge of subclasses.)
  195. */
  196. void init() {
  197. }
  198. /**
  199. * Initialize the hashing mask value. We defer initialization until we
  200. * really need it.
  201. */
  202. final boolean initHashSeedAsNeeded(int capacity) {
  203. boolean currentAltHashing = hashSeed != 0;
  204. boolean useAltHashing = sun.misc.VM.isBooted() &&
  205. (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
  206. boolean switching = currentAltHashing ^ useAltHashing;
  207. if (switching) {
  208. hashSeed = useAltHashing
  209. ? sun.misc.Hashing.randomHashSeed(this)
  210. : 0;
  211. }
  212. return switching;
  213. }
  214. /**
  215. * Retrieve object hash code and applies a supplemental hash function to the
  216. * result hash, which defends against poor quality hash functions. This is
  217. * critical because HashMap uses power-of-two length hash tables, that
  218. * otherwise encounter collisions for hashCodes that do not differ
  219. * in lower bits. Note: Null keys always map to hash 0, thus index 0.
  220. */
  221. final int hash(Object k) {
  222. int h = hashSeed;
  223. if (0 != h && k instanceof String) {
  224. return sun.misc.Hashing.stringHash32((String) k);
  225. }
  226. h ^= k.hashCode();
  227. // This function ensures that hashCodes that differ only by
  228. // constant multiples at each bit position have a bounded
  229. // number of collisions (approximately 8 at default load factor).
  230. h ^= (h >>> 20) ^ (h >>> 12);
  231. return h ^ (h >>> 7) ^ (h >>> 4);
  232. }
  233. /**
  234. * Returns index for hash code h.
  235. */
  236. static int indexFor(int h, int length) {
  237. // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
  238. return h & (length-1);
  239. }
  240. /**
  241. * Returns the number of key-value mappings in this map.
  242. *
  243. * @return the number of key-value mappings in this map
  244. */
  245. public int size() {
  246. return size;
  247. }
  248. /**
  249. * Returns <tt>true</tt> if this map contains no key-value mappings.
  250. *
  251. * @return <tt>true</tt> if this map contains no key-value mappings
  252. */
  253. public boolean isEmpty() {
  254. return size == 0;
  255. }
  256. /**
  257. * Returns the value to which the specified key is mapped,
  258. * or {@code null} if this map contains no mapping for the key.
  259. *
  260. * <p>More formally, if this map contains a mapping from a key
  261. * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
  262. * key.equals(k))}, then this method returns {@code v}; otherwise
  263. * it returns {@code null}. (There can be at most one such mapping.)
  264. *
  265. * <p>A return value of {@code null} does not <i>necessarily</i>
  266. * indicate that the map contains no mapping for the key; it's also
  267. * possible that the map explicitly maps the key to {@code null}.
  268. * The {@link #containsKey containsKey} operation may be used to
  269. * distinguish these two cases.
  270. *
  271. * @see #put(Object, Object)
  272. */
  273. public V get(Object key) {
  274. if (key == null)
  275. return getForNullKey();
  276. Entry<K,V> entry = getEntry(key);
  277. return null == entry ? null : entry.getValue();
  278. }
  279. /**
  280. * Offloaded version of get() to look up null keys. Null keys map
  281. * to index 0. This null case is split out into separate methods
  282. * for the sake of performance in the two most commonly used
  283. * operations (get and put), but incorporated with conditionals in
  284. * others.
  285. */
  286. private V getForNullKey() {
  287. if (size == 0) {
  288. return null;
  289. }
  290. for (Entry<K,V> e = table[0]; e != null; e = e.next) {
  291. if (e.key == null)
  292. return e.value;
  293. }
  294. return null;
  295. }
  296. /**
  297. * Returns <tt>true</tt> if this map contains a mapping for the
  298. * specified key.
  299. *
  300. * @param key The key whose presence in this map is to be tested
  301. * @return <tt>true</tt> if this map contains a mapping for the specified
  302. * key.
  303. */
  304. public boolean containsKey(Object key) {
  305. return getEntry(key) != null;
  306. }
  307. /**
  308. * Returns the entry associated with the specified key in the
  309. * HashMap. Returns null if the HashMap contains no mapping
  310. * for the key.
  311. */
  312. final Entry<K,V> getEntry(Object key) {
  313. if (size == 0) {
  314. return null;
  315. }
  316. int hash = (key == null) ? 0 : hash(key);
  317. for (Entry<K,V> e = table[indexFor(hash, table.length)];
  318. e != null;
  319. e = e.next) {
  320. Object k;
  321. if (e.hash == hash &&
  322. ((k = e.key) == key || (key != null && key.equals(k))))
  323. return e;
  324. }
  325. return null;
  326. }
  327. /**
  328. * Associates the specified value with the specified key in this map.
  329. * If the map previously contained a mapping for the key, the old
  330. * value is replaced.
  331. *
  332. * @param key key with which the specified value is to be associated
  333. * @param value value to be associated with the specified key
  334. * @return the previous value associated with <tt>key</tt>, or
  335. * <tt>null</tt> if there was no mapping for <tt>key</tt>.
  336. * (A <tt>null</tt> return can also indicate that the map
  337. * previously associated <tt>null</tt> with <tt>key</tt>.)
  338. */
  339. public V put(K key, V value) {
  340. if (table == EMPTY_TABLE) {
  341. inflateTable(threshold);
  342. }
  343. if (key == null)
  344. return putForNullKey(value);
  345. int hash = hash(key);
  346. int i = indexFor(hash, table.length);
  347. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  348. Object k;
  349. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  350. V oldValue = e.value;
  351. e.value = value;
  352. e.recordAccess(this);
  353. return oldValue;
  354. }
  355. }
  356. modCount++;
  357. addEntry(hash, key, value, i);
  358. return null;
  359. }
  360. /**
  361. * Offloaded version of put for null keys
  362. */
  363. private V putForNullKey(V value) {
  364. for (Entry<K,V> e = table[0]; e != null; e = e.next) {
  365. if (e.key == null) {
  366. V oldValue = e.value;
  367. e.value = value;
  368. e.recordAccess(this);
  369. return oldValue;
  370. }
  371. }
  372. modCount++;
  373. addEntry(0, null, value, 0);
  374. return null;
  375. }
  376. /**
  377. * This method is used instead of put by constructors and
  378. * pseudoconstructors (clone, readObject). It does not resize the table,
  379. * check for comodification, etc. It calls createEntry rather than
  380. * addEntry.
  381. */
  382. private void putForCreate(K key, V value) {
  383. int hash = null == key ? 0 : hash(key);
  384. int i = indexFor(hash, table.length);
  385. /**
  386. * Look for preexisting entry for key. This will never happen for
  387. * clone or deserialize. It will only happen for construction if the
  388. * input Map is a sorted map whose ordering is inconsistent w/ equals.
  389. */
  390. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  391. Object k;
  392. if (e.hash == hash &&
  393. ((k = e.key) == key || (key != null && key.equals(k)))) {
  394. e.value = value;
  395. return;
  396. }
  397. }
  398. createEntry(hash, key, value, i);
  399. }
  400. private void putAllForCreate(Map<? extends K, ? extends V> m) {
  401. for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
  402. putForCreate(e.getKey(), e.getValue());
  403. }
  404. /**
  405. * Rehashes the contents of this map into a new array with a
  406. * larger capacity. This method is called automatically when the
  407. * number of keys in this map reaches its threshold.
  408. *
  409. * If current capacity is MAXIMUM_CAPACITY, this method does not
  410. * resize the map, but sets threshold to Integer.MAX_VALUE.
  411. * This has the effect of preventing future calls.
  412. *
  413. * @param newCapacity the new capacity, MUST be a power of two;
  414. * must be greater than current capacity unless current
  415. * capacity is MAXIMUM_CAPACITY (in which case value
  416. * is irrelevant).
  417. */
  418. void resize(int newCapacity) {
  419. Entry[] oldTable = table;
  420. int oldCapacity = oldTable.length;
  421. if (oldCapacity == MAXIMUM_CAPACITY) {
  422. threshold = Integer.MAX_VALUE;
  423. return;
  424. }
  425. Entry[] newTable = new Entry[newCapacity];
  426. transfer(newTable, initHashSeedAsNeeded(newCapacity));
  427. table = newTable;
  428. threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  429. }
  430. /**
  431. * Transfers all entries from current table to newTable.
  432. */
  433. void transfer(Entry[] newTable, boolean rehash) {
  434. int newCapacity = newTable.length;
  435. for (Entry<K,V> e : table) {
  436. while(null != e) {
  437. Entry<K,V> next = e.next;
  438. if (rehash) {
  439. e.hash = null == e.key ? 0 : hash(e.key);
  440. }
  441. int i = indexFor(e.hash, newCapacity);
  442. e.next = newTable[i];
  443. newTable[i] = e;
  444. e = next;
  445. }
  446. }
  447. }
  448. /**
  449. * Copies all of the mappings from the specified map to this map.
  450. * These mappings will replace any mappings that this map had for
  451. * any of the keys currently in the specified map.
  452. *
  453. * @param m mappings to be stored in this map
  454. * @throws NullPointerException if the specified map is null
  455. */
  456. public void putAll(Map<? extends K, ? extends V> m) {
  457. int numKeysToBeAdded = m.size();
  458. if (numKeysToBeAdded == 0)
  459. return;
  460. if (table == EMPTY_TABLE) {
  461. inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
  462. }
  463. /*
  464. * Expand the map if the map if the number of mappings to be added
  465. * is greater than or equal to threshold. This is conservative; the
  466. * obvious condition is (m.size() + size) >= threshold, but this
  467. * condition could result in a map with twice the appropriate capacity,
  468. * if the keys to be added overlap with the keys already in this map.
  469. * By using the conservative calculation, we subject ourself
  470. * to at most one extra resize.
  471. */
  472. if (numKeysToBeAdded > threshold) {
  473. int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
  474. if (targetCapacity > MAXIMUM_CAPACITY)
  475. targetCapacity = MAXIMUM_CAPACITY;
  476. int newCapacity = table.length;
  477. while (newCapacity < targetCapacity)
  478. newCapacity <<= 1;
  479. if (newCapacity > table.length)
  480. resize(newCapacity);
  481. }
  482. for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
  483. put(e.getKey(), e.getValue());
  484. }
  485. /**
  486. * Removes the mapping for the specified key from this map if present.
  487. *
  488. * @param key key whose mapping is to be removed from the map
  489. * @return the previous value associated with <tt>key</tt>, or
  490. * <tt>null</tt> if there was no mapping for <tt>key</tt>.
  491. * (A <tt>null</tt> return can also indicate that the map
  492. * previously associated <tt>null</tt> with <tt>key</tt>.)
  493. */
  494. public V remove(Object key) {
  495. Entry<K,V> e = removeEntryForKey(key);
  496. return (e == null ? null : e.value);
  497. }
  498. /**
  499. * Removes and returns the entry associated with the specified key
  500. * in the HashMap. Returns null if the HashMap contains no mapping
  501. * for this key.
  502. */
  503. final Entry<K,V> removeEntryForKey(Object key) {
  504. if (size == 0) {
  505. return null;
  506. }
  507. int hash = (key == null) ? 0 : hash(key);
  508. int i = indexFor(hash, table.length);
  509. Entry<K,V> prev = table[i];
  510. Entry<K,V> e = prev;
  511. while (e != null) {
  512. Entry<K,V> next = e.next;
  513. Object k;
  514. if (e.hash == hash &&
  515. ((k = e.key) == key || (key != null && key.equals(k)))) {
  516. modCount++;
  517. size--;
  518. if (prev == e)
  519. table[i] = next;
  520. else
  521. prev.next = next;
  522. e.recordRemoval(this);
  523. return e;
  524. }
  525. prev = e;
  526. e = next;
  527. }
  528. return e;
  529. }
  530. /**
  531. * Special version of remove for EntrySet using {@code Map.Entry.equals()}
  532. * for matching.
  533. */
  534. final Entry<K,V> removeMapping(Object o) {
  535. if (size == 0 || !(o instanceof Map.Entry))
  536. return null;
  537. Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
  538. Object key = entry.getKey();
  539. int hash = (key == null) ? 0 : hash(key);
  540. int i = indexFor(hash, table.length);
  541. Entry<K,V> prev = table[i];
  542. Entry<K,V> e = prev;
  543. while (e != null) {
  544. Entry<K,V> next = e.next;
  545. if (e.hash == hash && e.equals(entry)) {
  546. modCount++;
  547. size--;
  548. if (prev == e)
  549. table[i] = next;
  550. else
  551. prev.next = next;
  552. e.recordRemoval(this);
  553. return e;
  554. }
  555. prev = e;
  556. e = next;
  557. }
  558. return e;
  559. }
  560. /**
  561. * Removes all of the mappings from this map.
  562. * The map will be empty after this call returns.
  563. */
  564. public void clear() {
  565. modCount++;
  566. Arrays.fill(table, null);
  567. size = 0;
  568. }
  569. /**
  570. * Returns <tt>true</tt> if this map maps one or more keys to the
  571. * specified value.
  572. *
  573. * @param value value whose presence in this map is to be tested
  574. * @return <tt>true</tt> if this map maps one or more keys to the
  575. * specified value
  576. */
  577. public boolean containsValue(Object value) {
  578. if (value == null)
  579. return containsNullValue();
  580. Entry[] tab = table;
  581. for (int i = 0; i < tab.length ; i++)
  582. for (Entry e = tab[i] ; e != null ; e = e.next)
  583. if (value.equals(e.value))
  584. return true;
  585. return false;
  586. }
  587. /**
  588. * Special-case code for containsValue with null argument
  589. */
  590. private boolean containsNullValue() {
  591. Entry[] tab = table;
  592. for (int i = 0; i < tab.length ; i++)
  593. for (Entry e = tab[i] ; e != null ; e = e.next)
  594. if (e.value == null)
  595. return true;
  596. return false;
  597. }
  598. /**
  599. * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
  600. * values themselves are not cloned.
  601. *
  602. * @return a shallow copy of this map
  603. */
  604. public Object clone() {
  605. JsonHashMap<K,V> result = null;
  606. try {
  607. result = (JsonHashMap<K,V>)super.clone();
  608. } catch (CloneNotSupportedException e) {
  609. // assert false;
  610. }
  611. if (result.table != EMPTY_TABLE) {
  612. result.inflateTable(Math.min(
  613. (int) Math.min(
  614. size * Math.min(1 / loadFactor, 4.0f),
  615. // we have limits...
  616. JsonHashMap.MAXIMUM_CAPACITY),
  617. table.length));
  618. }
  619. result.entrySet = null;
  620. result.modCount = 0;
  621. result.size = 0;
  622. result.init();
  623. result.putAllForCreate(this);
  624. return result;
  625. }
  626. static class Entry<K,V> implements Map.Entry<K,V> {
  627. final K key;
  628. V value;
  629. Entry<K,V> next;
  630. int hash;
  631. /**
  632. * Creates new entry.
  633. */
  634. Entry(int h, K k, V v, Entry<K,V> n) {
  635. value = v;
  636. next = n;
  637. key = k;
  638. hash = h;
  639. }
  640. public final K getKey() {
  641. return key;
  642. }
  643. public final V getValue() {
  644. return value;
  645. }
  646. public final V setValue(V newValue) {
  647. V oldValue = value;
  648. value = newValue;
  649. return oldValue;
  650. }
  651. public final boolean equals(Object o) {
  652. if (!(o instanceof Map.Entry))
  653. return false;
  654. Map.Entry e = (Map.Entry)o;
  655. Object k1 = getKey();
  656. Object k2 = e.getKey();
  657. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  658. Object v1 = getValue();
  659. Object v2 = e.getValue();
  660. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  661. return true;
  662. }
  663. return false;
  664. }
  665. public final int hashCode() {
  666. return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
  667. }
  668. public String toString() {
  669. System.out.println(getValue() instanceof String);
  670. if(getValue() instanceof String)
  671. return getKey() + ":\'" + getValue()+"\'";
  672. return getKey() + ":" + getValue();
  673. }
  674. /**
  675. * This method is invoked whenever the value in an entry is
  676. * overwritten by an invocation of put(k,v) for a key k that's already
  677. * in the HashMap.
  678. */
  679. void recordAccess(JsonHashMap<K, V> jsonHashMap) {
  680. }
  681. /**
  682. * This method is invoked whenever the entry is
  683. * removed from the table.
  684. */
  685. void recordRemoval(JsonHashMap<K, V> jsonHashMap) {
  686. }
  687. }
  688. /**
  689. * Adds a new entry with the specified key, value and hash code to
  690. * the specified bucket. It is the responsibility of this
  691. * method to resize the table if appropriate.
  692. *
  693. * Subclass overrides this to alter the behavior of put method.
  694. */
  695. void addEntry(int hash, K key, V value, int bucketIndex) {
  696. if ((size >= threshold) && (null != table[bucketIndex])) {
  697. resize(2 * table.length);
  698. hash = (null != key) ? hash(key) : 0;
  699. bucketIndex = indexFor(hash, table.length);
  700. }
  701. createEntry(hash, key, value, bucketIndex);
  702. }
  703. /**
  704. * Like addEntry except that this version is used when creating entries
  705. * as part of Map construction or "pseudo-construction" (cloning,
  706. * deserialization). This version needn't worry about resizing the table.
  707. *
  708. * Subclass overrides this to alter the behavior of HashMap(Map),
  709. * clone, and readObject.
  710. */
  711. void createEntry(int hash, K key, V value, int bucketIndex) {
  712. Entry<K,V> e = table[bucketIndex];
  713. table[bucketIndex] = new Entry<K, V>(hash, key, value, e);
  714. size++;
  715. }
  716. private abstract class HashIterator<E> implements Iterator<E> {
  717. Entry<K,V> next; // next entry to return
  718. int expectedModCount; // For fast-fail
  719. int index; // current slot
  720. Entry<K,V> current; // current entry
  721. HashIterator() {
  722. expectedModCount = modCount;
  723. if (size > 0) { // advance to first entry
  724. Entry[] t = table;
  725. while (index < t.length && (next = t[index++]) == null)
  726. ;
  727. }
  728. }
  729. public final boolean hasNext() {
  730. return next != null;
  731. }
  732. final Entry<K,V> nextEntry() {
  733. if (modCount != expectedModCount)
  734. throw new ConcurrentModificationException();
  735. Entry<K,V> e = next;
  736. if (e == null)
  737. throw new NoSuchElementException();
  738. if ((next = e.next) == null) {
  739. Entry[] t = table;
  740. while (index < t.length && (next = t[index++]) == null)
  741. ;
  742. }
  743. current = e;
  744. return e;
  745. }
  746. public void remove() {
  747. if (current == null)
  748. throw new IllegalStateException();
  749. if (modCount != expectedModCount)
  750. throw new ConcurrentModificationException();
  751. Object k = current.key;
  752. current = null;
  753. JsonHashMap.this.removeEntryForKey(k);
  754. expectedModCount = modCount;
  755. }
  756. }
  757. private final class ValueIterator extends HashIterator<V> {
  758. public V next() {
  759. return nextEntry().value;
  760. }
  761. }
  762. private final class KeyIterator extends HashIterator<K> {
  763. public K next() {
  764. return nextEntry().getKey();
  765. }
  766. }
  767. private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
  768. public Map.Entry<K,V> next() {
  769. return nextEntry();
  770. }
  771. }
  772. // Subclass overrides these to alter behavior of views' iterator() method
  773. Iterator<K> newKeyIterator() {
  774. return new KeyIterator();
  775. }
  776. Iterator<V> newValueIterator() {
  777. return new ValueIterator();
  778. }
  779. Iterator<Map.Entry<K,V>> newEntryIterator() {
  780. return new EntryIterator();
  781. }
  782. // Views
  783. private transient Set<Map.Entry<K,V>> entrySet = null;
  784. /**
  785. * Returns a {@link Set} view of the keys contained in this map.
  786. * The set is backed by the map, so changes to the map are
  787. * reflected in the set, and vice-versa. If the map is modified
  788. * while an iteration over the set is in progress (except through
  789. * the iterator's own <tt>remove</tt> operation), the results of
  790. * the iteration are undefined. The set supports element removal,
  791. * which removes the corresponding mapping from the map, via the
  792. * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
  793. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
  794. * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
  795. * operations.
  796. */
  797. transient volatile Set<K> keySet = null;
  798. public Set<K> keySet() {
  799. Set<K> ks = keySet;
  800. return (ks != null ? ks : (keySet = new KeySet()));
  801. }
  802. private final class KeySet extends AbstractSet<K> {
  803. public Iterator<K> iterator() {
  804. return newKeyIterator();
  805. }
  806. public int size() {
  807. return size;
  808. }
  809. public boolean contains(Object o) {
  810. return containsKey(o);
  811. }
  812. public boolean remove(Object o) {
  813. return JsonHashMap.this.removeEntryForKey(o) != null;
  814. }
  815. public void clear() {
  816. JsonHashMap.this.clear();
  817. }
  818. }
  819. /**
  820. * Returns a {@link Collection} view of the values contained in this map.
  821. * The collection is backed by the map, so changes to the map are
  822. * reflected in the collection, and vice-versa. If the map is
  823. * modified while an iteration over the collection is in progress
  824. * (except through the iterator's own <tt>remove</tt> operation),
  825. * the results of the iteration are undefined. The collection
  826. * supports element removal, which removes the corresponding
  827. * mapping from the map, via the <tt>Iterator.remove</tt>,
  828. * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
  829. * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
  830. * support the <tt>add</tt> or <tt>addAll</tt> operations.
  831. */
  832. transient volatile Collection<V> values = null;
  833. public Collection<V> values() {
  834. Collection<V> vs = values;
  835. return (vs != null ? vs : (values = new Values()));
  836. }
  837. private final class Values extends AbstractCollection<V> {
  838. public Iterator<V> iterator() {
  839. return newValueIterator();
  840. }
  841. public int size() {
  842. return size;
  843. }
  844. public boolean contains(Object o) {
  845. return containsValue(o);
  846. }
  847. public void clear() {
  848. JsonHashMap.this.clear();
  849. }
  850. }
  851. /**
  852. * Returns a {@link Set} view of the mappings contained in this map.
  853. * The set is backed by the map, so changes to the map are
  854. * reflected in the set, and vice-versa. If the map is modified
  855. * while an iteration over the set is in progress (except through
  856. * the iterator's own <tt>remove</tt> operation, or through the
  857. * <tt>setValue</tt> operation on a map entry returned by the
  858. * iterator) the results of the iteration are undefined. The set
  859. * supports element removal, which removes the corresponding
  860. * mapping from the map, via the <tt>Iterator.remove</tt>,
  861. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
  862. * <tt>clear</tt> operations. It does not support the
  863. * <tt>add</tt> or <tt>addAll</tt> operations.
  864. *
  865. * @return a set view of the mappings contained in this map
  866. */
  867. public Set<Map.Entry<K,V>> entrySet() {
  868. return entrySet0();
  869. }
  870. private Set<Map.Entry<K,V>> entrySet0() {
  871. Set<Map.Entry<K,V>> es = entrySet;
  872. return es != null ? es : (entrySet = new EntrySet());
  873. }
  874. private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
  875. public Iterator<Map.Entry<K,V>> iterator() {
  876. return newEntryIterator();
  877. }
  878. public boolean contains(Object o) {
  879. if (!(o instanceof Map.Entry))
  880. return false;
  881. Map.Entry<K,V> e = (Map.Entry<K,V>) o;
  882. Entry<K,V> candidate = getEntry(e.getKey());
  883. return candidate != null && candidate.equals(e);
  884. }
  885. public boolean remove(Object o) {
  886. return removeMapping(o) != null;
  887. }
  888. public int size() {
  889. return size;
  890. }
  891. public void clear() {
  892. JsonHashMap.this.clear();
  893. }
  894. }
  895. /**
  896. * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
  897. * serialize it).
  898. *
  899. * @serialData The <i>capacity</i> of the HashMap (the length of the
  900. * bucket array) is emitted (int), followed by the
  901. * <i>size</i> (an int, the number of key-value
  902. * mappings), followed by the key (Object) and value (Object)
  903. * for each key-value mapping. The key-value mappings are
  904. * emitted in no particular order.
  905. */
  906. private void writeObject(java.io.ObjectOutputStream s)
  907. throws IOException
  908. {
  909. // Write out the threshold, loadfactor, and any hidden stuff
  910. s.defaultWriteObject();
  911. // Write out number of buckets
  912. if (table==EMPTY_TABLE) {
  913. s.writeInt(roundUpToPowerOf2(threshold));
  914. } else {
  915. s.writeInt(table.length);
  916. }
  917. // Write out size (number of Mappings)
  918. s.writeInt(size);
  919. // Write out keys and values (alternating)
  920. if (size > 0) {
  921. for(Map.Entry<K,V> e : entrySet0()) {
  922. s.writeObject(e.getKey());
  923. s.writeObject(e.getValue());
  924. }
  925. }
  926. }
  927. private static final long serialVersionUID = 362498820763181265L;
  928. /**
  929. * Reconstitute the {@code HashMap} instance from a stream (i.e.,
  930. * deserialize it).
  931. */
  932. private void readObject(java.io.ObjectInputStream s)
  933. throws IOException, ClassNotFoundException
  934. {
  935. // Read in the threshold (ignored), loadfactor, and any hidden stuff
  936. s.defaultReadObject();
  937. if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
  938. throw new InvalidObjectException("Illegal load factor: " +
  939. loadFactor);
  940. }
  941. // set other fields that need values
  942. table = (Entry<K,V>[]) EMPTY_TABLE;
  943. // Read in number of buckets
  944. s.readInt(); // ignored.
  945. // Read number of mappings
  946. int mappings = s.readInt();
  947. if (mappings < 0)
  948. throw new InvalidObjectException("Illegal mappings count: " +
  949. mappings);
  950. // capacity chosen by number of mappings and desired load (if >= 0.25)
  951. int capacity = (int) Math.min(
  952. mappings * Math.min(1 / loadFactor, 4.0f),
  953. // we have limits...
  954. JsonHashMap.MAXIMUM_CAPACITY);
  955. // allocate the bucket array;
  956. if (mappings > 0) {
  957. inflateTable(capacity);
  958. } else {
  959. threshold = capacity;
  960. }
  961. init(); // Give subclass a chance to do its thing.
  962. // Read the keys and values, and put the mappings in the HashMap
  963. for (int i = 0; i < mappings; i++) {
  964. K key = (K) s.readObject();
  965. V value = (V) s.readObject();
  966. putForCreate(key, value);
  967. }
  968. }
  969. // These methods are used when serializing HashSets
  970. int capacity() { return table.length; }
  971. float loadFactor() { return loadFactor; }
  972. }