source: trunk/src/gcc/libjava/java/util/HashMap.java@ 741

Last change on this file since 741 was 2, checked in by bird, 23 years ago

Initial revision

  • Property cvs2svn:cvs-rev set to 1.1
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 25.4 KB
Line 
1/* HashMap.java -- a class providing a basic hashtable data structure,
2 mapping Object --> Object
3 Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
4
5This file is part of GNU Classpath.
6
7GNU Classpath is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 2, or (at your option)
10any later version.
11
12GNU Classpath is distributed in the hope that it will be useful, but
13WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GNU Classpath; see the file COPYING. If not, write to the
19Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
2002111-1307 USA.
21
22Linking this library statically or dynamically with other modules is
23making a combined work based on this library. Thus, the terms and
24conditions of the GNU General Public License cover the whole
25combination.
26
27As a special exception, the copyright holders of this library give you
28permission to link this library with independent modules to produce an
29executable, regardless of the license terms of these independent
30modules, and to copy and distribute the resulting executable under
31terms of your choice, provided that you also meet, for each linked
32independent module, the terms and conditions of the license of that
33module. An independent module is a module which is not derived from
34or based on this library. If you modify this library, you may extend
35this exception to your version of the library, but you are not
36obligated to do so. If you do not wish to do so, delete this
37exception statement from your version. */
38
39
40package java.util;
41
42import java.io.IOException;
43import java.io.Serializable;
44import java.io.ObjectInputStream;
45import java.io.ObjectOutputStream;
46
47// NOTE: This implementation is very similar to that of Hashtable. If you fix
48// a bug in here, chances are you should make a similar change to the Hashtable
49// code.
50
51// NOTE: This implementation has some nasty coding style in order to
52// support LinkedHashMap, which extends this.
53
54/**
55 * This class provides a hashtable-backed implementation of the
56 * Map interface.
57 * <p>
58 *
59 * It uses a hash-bucket approach; that is, hash collisions are handled
60 * by linking the new node off of the pre-existing node (or list of
61 * nodes). In this manner, techniques such as linear probing (which
62 * can cause primary clustering) and rehashing (which does not fit very
63 * well with Java's method of precomputing hash codes) are avoided.
64 * <p>
65 *
66 * Under ideal circumstances (no collisions), HashMap offers O(1)
67 * performance on most operations (<code>containsValue()</code> is,
68 * of course, O(n)). In the worst case (all keys map to the same
69 * hash code -- very unlikely), most operations are O(n).
70 * <p>
71 *
72 * HashMap is part of the JDK1.2 Collections API. It differs from
73 * Hashtable in that it accepts the null key and null values, and it
74 * does not support "Enumeration views." Also, it is not synchronized;
75 * if you plan to use it in multiple threads, consider using:<br>
76 * <code>Map m = Collections.synchronizedMap(new HashMap(...));</code>
77 * <p>
78 *
79 * The iterators are <i>fail-fast</i>, meaning that any structural
80 * modification, except for <code>remove()</code> called on the iterator
81 * itself, cause the iterator to throw a
82 * <code>ConcurrentModificationException</code> rather than exhibit
83 * non-deterministic behavior.
84 *
85 * @author Jon Zeppieri
86 * @author Jochen Hoenicke
87 * @author Bryce McKinlay
88 * @author Eric Blake <[email protected]>
89 * @see Object#hashCode()
90 * @see Collection
91 * @see Map
92 * @see TreeMap
93 * @see LinkedHashMap
94 * @see IdentityHashMap
95 * @see Hashtable
96 * @since 1.2
97 * @status updated to 1.4
98 */
99public class HashMap extends AbstractMap
100 implements Map, Cloneable, Serializable
101{
102 /**
103 * Default number of buckets. This is the value the JDK 1.3 uses. Some
104 * early documentation specified this value as 101. That is incorrect.
105 * Package visible for use by HashSet.
106 */
107 static final int DEFAULT_CAPACITY = 11;
108
109 /**
110 * The default load factor; this is explicitly specified by the spec.
111 * Package visible for use by HashSet.
112 */
113 static final float DEFAULT_LOAD_FACTOR = 0.75f;
114
115 /**
116 * Compatible with JDK 1.2.
117 */
118 private static final long serialVersionUID = 362498820763181265L;
119
120 /**
121 * The rounded product of the capacity and the load factor; when the number
122 * of elements exceeds the threshold, the HashMap calls
123 * <code>rehash()</code>.
124 * @serial the threshold for rehashing
125 */
126 private int threshold;
127
128 /**
129 * Load factor of this HashMap: used in computing the threshold.
130 * Package visible for use by HashSet.
131 * @serial the load factor
132 */
133 final float loadFactor;
134
135 /**
136 * Array containing the actual key-value mappings.
137 * Package visible for use by nested and subclasses.
138 */
139 transient HashEntry[] buckets;
140
141 /**
142 * Counts the number of modifications this HashMap has undergone, used
143 * by Iterators to know when to throw ConcurrentModificationExceptions.
144 * Package visible for use by nested and subclasses.
145 */
146 transient int modCount;
147
148 /**
149 * The size of this HashMap: denotes the number of key-value pairs.
150 * Package visible for use by nested and subclasses.
151 */
152 transient int size;
153
154 /**
155 * The cache for {@link #entrySet()}.
156 */
157 private transient Set entries;
158
159 /**
160 * Class to represent an entry in the hash table. Holds a single key-value
161 * pair. Package visible for use by subclass.
162 *
163 * @author Eric Blake <[email protected]>
164 */
165 static class HashEntry extends BasicMapEntry
166 {
167 /**
168 * The next entry in the linked list. Package visible for use by subclass.
169 */
170 HashEntry next;
171
172 /**
173 * Simple constructor.
174 * @param key the key
175 * @param value the value
176 */
177 HashEntry(Object key, Object value)
178 {
179 super(key, value);
180 }
181
182 /**
183 * Called when this entry is removed from the map. This version simply
184 * returns the value, but in LinkedHashMap, it must also do bookkeeping.
185 *
186 * @return the value of this key as it is removed
187 */
188 Object cleanup()
189 {
190 return value;
191 }
192 }
193
194 /**
195 * Construct a new HashMap with the default capacity (11) and the default
196 * load factor (0.75).
197 */
198 public HashMap()
199 {
200 this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
201 }
202
203 /**
204 * Construct a new HashMap from the given Map, with initial capacity
205 * the greater of the size of <code>m</code> or the default of 11.
206 * <p>
207 *
208 * Every element in Map m will be put into this new HashMap.
209 *
210 * @param m a Map whose key / value pairs will be put into the new HashMap.
211 * <b>NOTE: key / value pairs are not cloned in this constructor.</b>
212 * @throws NullPointerException if m is null
213 */
214 public HashMap(Map m)
215 {
216 this(Math.max(m.size() * 2, DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);
217 putAllInternal(m);
218 }
219
220 /**
221 * Construct a new HashMap with a specific inital capacity and
222 * default load factor of 0.75.
223 *
224 * @param initialCapacity the initial capacity of this HashMap (&gt;=0)
225 * @throws IllegalArgumentException if (initialCapacity &lt; 0)
226 */
227 public HashMap(int initialCapacity)
228 {
229 this(initialCapacity, DEFAULT_LOAD_FACTOR);
230 }
231
232 /**
233 * Construct a new HashMap with a specific inital capacity and load factor.
234 *
235 * @param initialCapacity the initial capacity (&gt;=0)
236 * @param loadFactor the load factor (&gt; 0, not NaN)
237 * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||
238 * ! (loadFactor &gt; 0.0)
239 */
240 public HashMap(int initialCapacity, float loadFactor)
241 {
242 if (initialCapacity < 0)
243 throw new IllegalArgumentException("Illegal Capacity: "
244 + initialCapacity);
245 if (! (loadFactor > 0)) // check for NaN too
246 throw new IllegalArgumentException("Illegal Load: " + loadFactor);
247
248 if (initialCapacity == 0)
249 initialCapacity = 1;
250 buckets = new HashEntry[initialCapacity];
251 this.loadFactor = loadFactor;
252 threshold = (int) (initialCapacity * loadFactor);
253 }
254
255 /**
256 * Returns the number of kay-value mappings currently in this Map.
257 *
258 * @return the size
259 */
260 public int size()
261 {
262 return size;
263 }
264
265 /**
266 * Returns true if there are no key-value mappings currently in this Map.
267 *
268 * @return <code>size() == 0</code>
269 */
270 public boolean isEmpty()
271 {
272 return size == 0;
273 }
274
275 /**
276 * Return the value in this HashMap associated with the supplied key,
277 * or <code>null</code> if the key maps to nothing. NOTE: Since the value
278 * could also be null, you must use containsKey to see if this key
279 * actually maps to something.
280 *
281 * @param key the key for which to fetch an associated value
282 * @return what the key maps to, if present
283 * @see #put(Object, Object)
284 * @see #containsKey(Object)
285 */
286 public Object get(Object key)
287 {
288 int idx = hash(key);
289 HashEntry e = buckets[idx];
290 while (e != null)
291 {
292 if (equals(key, e.key))
293 return e.value;
294 e = e.next;
295 }
296 return null;
297 }
298
299 /**
300 * Returns true if the supplied object <code>equals()</code> a key
301 * in this HashMap.
302 *
303 * @param key the key to search for in this HashMap
304 * @return true if the key is in the table
305 * @see #containsValue(Object)
306 */
307 public boolean containsKey(Object key)
308 {
309 int idx = hash(key);
310 HashEntry e = buckets[idx];
311 while (e != null)
312 {
313 if (equals(key, e.key))
314 return true;
315 e = e.next;
316 }
317 return false;
318 }
319
320 /**
321 * Puts the supplied value into the Map, mapped by the supplied key.
322 * The value may be retrieved by any object which <code>equals()</code>
323 * this key. NOTE: Since the prior value could also be null, you must
324 * first use containsKey if you want to see if you are replacing the
325 * key's mapping.
326 *
327 * @param key the key used to locate the value
328 * @param value the value to be stored in the HashMap
329 * @return the prior mapping of the key, or null if there was none
330 * @see #get(Object)
331 * @see Object#equals(Object)
332 */
333 public Object put(Object key, Object value)
334 {
335 int idx = hash(key);
336 HashEntry e = buckets[idx];
337
338 while (e != null)
339 {
340 if (equals(key, e.key))
341 // Must use this method for necessary bookkeeping in LinkedHashMap.
342 return e.setValue(value);
343 else
344 e = e.next;
345 }
346
347 // At this point, we know we need to add a new entry.
348 modCount++;
349 if (++size > threshold)
350 {
351 rehash();
352 // Need a new hash value to suit the bigger table.
353 idx = hash(key);
354 }
355
356 // LinkedHashMap cannot override put(), hence this call.
357 addEntry(key, value, idx, true);
358 return null;
359 }
360
361 /**
362 * Copies all elements of the given map into this hashtable. If this table
363 * already has a mapping for a key, the new mapping replaces the current
364 * one.
365 *
366 * @param m the map to be hashed into this
367 */
368 public void putAll(Map m)
369 {
370 Iterator itr = m.entrySet().iterator();
371
372 for (int msize = m.size(); msize > 0; msize--)
373 {
374 Map.Entry e = (Map.Entry) itr.next();
375 // Optimize in case the Entry is one of our own.
376 if (e instanceof BasicMapEntry)
377 {
378 BasicMapEntry entry = (BasicMapEntry) e;
379 put(entry.key, entry.value);
380 }
381 else
382 {
383 put(e.getKey(), e.getValue());
384 }
385 }
386 }
387
388 /**
389 * Removes from the HashMap and returns the value which is mapped by the
390 * supplied key. If the key maps to nothing, then the HashMap remains
391 * unchanged, and <code>null</code> is returned. NOTE: Since the value
392 * could also be null, you must use containsKey to see if you are
393 * actually removing a mapping.
394 *
395 * @param key the key used to locate the value to remove
396 * @return whatever the key mapped to, if present
397 */
398 public Object remove(Object key)
399 {
400 int idx = hash(key);
401 HashEntry e = buckets[idx];
402 HashEntry last = null;
403
404 while (e != null)
405 {
406 if (equals(key, e.key))
407 {
408 modCount++;
409 if (last == null)
410 buckets[idx] = e.next;
411 else
412 last.next = e.next;
413 size--;
414 // Method call necessary for LinkedHashMap to work correctly.
415 return e.cleanup();
416 }
417 last = e;
418 e = e.next;
419 }
420 return null;
421 }
422
423 /**
424 * Clears the Map so it has no keys. This is O(1).
425 */
426 public void clear()
427 {
428 if (size != 0)
429 {
430 modCount++;
431 Arrays.fill(buckets, null);
432 size = 0;
433 }
434 }
435
436 /**
437 * Returns true if this HashMap contains a value <code>o</code>, such that
438 * <code>o.equals(value)</code>.
439 *
440 * @param value the value to search for in this HashMap
441 * @return true if at least one key maps to the value
442 * @see containsKey(Object)
443 */
444 public boolean containsValue(Object value)
445 {
446 for (int i = buckets.length - 1; i >= 0; i--)
447 {
448 HashEntry e = buckets[i];
449 while (e != null)
450 {
451 if (equals(value, e.value))
452 return true;
453 e = e.next;
454 }
455 }
456 return false;
457 }
458
459 /**
460 * Returns a shallow clone of this HashMap. The Map itself is cloned,
461 * but its contents are not. This is O(n).
462 *
463 * @return the clone
464 */
465 public Object clone()
466 {
467 HashMap copy = null;
468 try
469 {
470 copy = (HashMap) super.clone();
471 }
472 catch (CloneNotSupportedException x)
473 {
474 // This is impossible.
475 }
476 copy.buckets = new HashEntry[buckets.length];
477 copy.putAllInternal(this);
478 // Clear the entry cache. AbstractMap.clone() does the others.
479 copy.entries = null;
480 return copy;
481 }
482
483 /**
484 * Returns a "set view" of this HashMap's keys. The set is backed by the
485 * HashMap, so changes in one show up in the other. The set supports
486 * element removal, but not element addition.
487 *
488 * @return a set view of the keys
489 * @see #values()
490 * @see #entrySet()
491 */
492 public Set keySet()
493 {
494 if (keys == null)
495 // Create an AbstractSet with custom implementations of those methods
496 // that can be overridden easily and efficiently.
497 keys = new AbstractSet()
498 {
499 public int size()
500 {
501 return size;
502 }
503
504 public Iterator iterator()
505 {
506 // Cannot create the iterator directly, because of LinkedHashMap.
507 return HashMap.this.iterator(KEYS);
508 }
509
510 public void clear()
511 {
512 HashMap.this.clear();
513 }
514
515 public boolean contains(Object o)
516 {
517 return containsKey(o);
518 }
519
520 public boolean remove(Object o)
521 {
522 // Test against the size of the HashMap to determine if anything
523 // really got removed. This is neccessary because the return value
524 // of HashMap.remove() is ambiguous in the null case.
525 int oldsize = size;
526 HashMap.this.remove(o);
527 return oldsize != size;
528 }
529 };
530 return keys;
531 }
532
533 /**
534 * Returns a "collection view" (or "bag view") of this HashMap's values.
535 * The collection is backed by the HashMap, so changes in one show up
536 * in the other. The collection supports element removal, but not element
537 * addition.
538 *
539 * @return a bag view of the values
540 * @see #keySet()
541 * @see #entrySet()
542 */
543 public Collection values()
544 {
545 if (values == null)
546 // We don't bother overriding many of the optional methods, as doing so
547 // wouldn't provide any significant performance advantage.
548 values = new AbstractCollection()
549 {
550 public int size()
551 {
552 return size;
553 }
554
555 public Iterator iterator()
556 {
557 // Cannot create the iterator directly, because of LinkedHashMap.
558 return HashMap.this.iterator(VALUES);
559 }
560
561 public void clear()
562 {
563 HashMap.this.clear();
564 }
565 };
566 return values;
567 }
568
569 /**
570 * Returns a "set view" of this HashMap's entries. The set is backed by
571 * the HashMap, so changes in one show up in the other. The set supports
572 * element removal, but not element addition.<p>
573 *
574 * Note that the iterators for all three views, from keySet(), entrySet(),
575 * and values(), traverse the HashMap in the same sequence.
576 *
577 * @return a set view of the entries
578 * @see #keySet()
579 * @see #values()
580 * @see Map.Entry
581 */
582 public Set entrySet()
583 {
584 if (entries == null)
585 // Create an AbstractSet with custom implementations of those methods
586 // that can be overridden easily and efficiently.
587 entries = new AbstractSet()
588 {
589 public int size()
590 {
591 return size;
592 }
593
594 public Iterator iterator()
595 {
596 // Cannot create the iterator directly, because of LinkedHashMap.
597 return HashMap.this.iterator(ENTRIES);
598 }
599
600 public void clear()
601 {
602 HashMap.this.clear();
603 }
604
605 public boolean contains(Object o)
606 {
607 return getEntry(o) != null;
608 }
609
610 public boolean remove(Object o)
611 {
612 HashEntry e = getEntry(o);
613 if (e != null)
614 {
615 HashMap.this.remove(e.key);
616 return true;
617 }
618 return false;
619 }
620 };
621 return entries;
622 }
623
624 /**
625 * Helper method for put, that creates and adds a new Entry. This is
626 * overridden in LinkedHashMap for bookkeeping purposes.
627 *
628 * @param key the key of the new Entry
629 * @param value the value
630 * @param idx the index in buckets where the new Entry belongs
631 * @param callRemove whether to call the removeEldestEntry method
632 * @see #put(Object, Object)
633 */
634 void addEntry(Object key, Object value, int idx, boolean callRemove)
635 {
636 HashEntry e = new HashEntry(key, value);
637
638 e.next = buckets[idx];
639 buckets[idx] = e;
640 }
641
642 /**
643 * Helper method for entrySet(), which matches both key and value
644 * simultaneously.
645 *
646 * @param o the entry to match
647 * @return the matching entry, if found, or null
648 * @see #entrySet()
649 */
650 private HashEntry getEntry(Object o)
651 {
652 if (!(o instanceof Map.Entry))
653 return null;
654 Map.Entry me = (Map.Entry) o;
655 int idx = hash(me.getKey());
656 HashEntry e = buckets[idx];
657 while (e != null)
658 {
659 if (e.equals(me))
660 return e;
661 e = e.next;
662 }
663 return null;
664 }
665
666 /**
667 * Helper method that returns an index in the buckets array for `key'
668 * based on its hashCode(). Package visible for use by subclasses.
669 *
670 * @param key the key
671 * @return the bucket number
672 */
673 final int hash(Object key)
674 {
675 return key == null ? 0 : Math.abs(key.hashCode() % buckets.length);
676 }
677
678 /**
679 * Generates a parameterized iterator. Must be overrideable, since
680 * LinkedHashMap iterates in a different order.
681 *
682 * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
683 * @return the appropriate iterator
684 */
685 Iterator iterator(int type)
686 {
687 return new HashIterator(type);
688 }
689
690 /**
691 * A simplified, more efficient internal implementation of putAll(). The
692 * Map constructor and clone() should not call putAll or put, in order to
693 * be compatible with the JDK implementation with respect to subclasses.
694 *
695 * @param m the map to initialize this from
696 */
697 void putAllInternal(Map m)
698 {
699 Iterator itr = m.entrySet().iterator();
700 int msize = m.size();
701 this.size = msize;
702
703 for (; msize > 0; msize--)
704 {
705 Map.Entry e = (Map.Entry) itr.next();
706 Object key = e.getKey();
707 int idx = hash(key);
708 addEntry(key, e.getValue(), idx, false);
709 }
710 }
711
712 /**
713 * Increases the size of the HashMap and rehashes all keys to new array
714 * indices; this is called when the addition of a new value would cause
715 * size() > threshold. Note that the existing Entry objects are reused in
716 * the new hash table.
717 * <p>
718 *
719 * This is not specified, but the new size is twice the current size plus
720 * one; this number is not always prime, unfortunately.
721 */
722 private void rehash()
723 {
724 HashEntry[] oldBuckets = buckets;
725
726 int newcapacity = (buckets.length * 2) + 1;
727 threshold = (int) (newcapacity * loadFactor);
728 buckets = new HashEntry[newcapacity];
729
730 for (int i = oldBuckets.length - 1; i >= 0; i--)
731 {
732 HashEntry e = oldBuckets[i];
733 while (e != null)
734 {
735 int idx = hash(e.key);
736 HashEntry dest = buckets[idx];
737
738 if (dest != null)
739 {
740 while (dest.next != null)
741 dest = dest.next;
742 dest.next = e;
743 }
744 else
745 {
746 buckets[idx] = e;
747 }
748
749 HashEntry next = e.next;
750 e.next = null;
751 e = next;
752 }
753 }
754 }
755
756 /**
757 * Serializes this object to the given stream.
758 *
759 * @param s the stream to write to
760 * @throws IOException if the underlying stream fails
761 * @serialData the <i>capacity</i>(int) that is the length of the
762 * bucket array, the <i>size</i>(int) of the hash map
763 * are emitted first. They are followed by size entries,
764 * each consisting of a key (Object) and a value (Object).
765 */
766 private void writeObject(ObjectOutputStream s) throws IOException
767 {
768 // Write the threshold and loadFactor fields.
769 s.defaultWriteObject();
770
771 s.writeInt(buckets.length);
772 s.writeInt(size);
773 // Avoid creating a wasted Set by creating the iterator directly.
774 Iterator it = iterator(ENTRIES);
775 while (it.hasNext())
776 {
777 HashEntry entry = (HashEntry) it.next();
778 s.writeObject(entry.key);
779 s.writeObject(entry.value);
780 }
781 }
782
783 /**
784 * Deserializes this object from the given stream.
785 *
786 * @param s the stream to read from
787 * @throws ClassNotFoundException if the underlying stream fails
788 * @throws IOException if the underlying stream fails
789 * @serialData the <i>capacity</i>(int) that is the length of the
790 * bucket array, the <i>size</i>(int) of the hash map
791 * are emitted first. They are followed by size entries,
792 * each consisting of a key (Object) and a value (Object).
793 */
794 private void readObject(ObjectInputStream s)
795 throws IOException, ClassNotFoundException
796 {
797 // Read the threshold and loadFactor fields.
798 s.defaultReadObject();
799
800 // Read and use capacity.
801 buckets = new HashEntry[s.readInt()];
802 int len = s.readInt();
803
804 // Read and use key/value pairs.
805 for ( ; len > 0; len--)
806 put(s.readObject(), s.readObject());
807 }
808
809 /**
810 * Iterate over HashMap's entries.
811 * This implementation is parameterized to give a sequential view of
812 * keys, values, or entries.
813 *
814 * @author Jon Zeppieri
815 */
816 private final class HashIterator implements Iterator
817 {
818 /**
819 * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
820 * or {@link #ENTRIES}.
821 */
822 private final int type;
823 /**
824 * The number of modifications to the backing HashMap that we know about.
825 */
826 private int knownMod = modCount;
827 /** The number of elements remaining to be returned by next(). */
828 private int count = size;
829 /** Current index in the physical hash table. */
830 private int idx = buckets.length;
831 /** The last Entry returned by a next() call. */
832 private HashEntry last;
833 /**
834 * The next entry that should be returned by next(). It is set to something
835 * if we're iterating through a bucket that contains multiple linked
836 * entries. It is null if next() needs to find a new bucket.
837 */
838 private HashEntry next;
839
840 /**
841 * Construct a new HashIterator with the supplied type.
842 * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
843 */
844 HashIterator(int type)
845 {
846 this.type = type;
847 }
848
849 /**
850 * Returns true if the Iterator has more elements.
851 * @return true if there are more elements
852 * @throws ConcurrentModificationException if the HashMap was modified
853 */
854 public boolean hasNext()
855 {
856 if (knownMod != modCount)
857 throw new ConcurrentModificationException();
858 return count > 0;
859 }
860
861 /**
862 * Returns the next element in the Iterator's sequential view.
863 * @return the next element
864 * @throws ConcurrentModificationException if the HashMap was modified
865 * @throws NoSuchElementException if there is none
866 */
867 public Object next()
868 {
869 if (knownMod != modCount)
870 throw new ConcurrentModificationException();
871 if (count == 0)
872 throw new NoSuchElementException();
873 count--;
874 HashEntry e = next;
875
876 while (e == null)
877 e = buckets[--idx];
878
879 next = e.next;
880 last = e;
881 if (type == VALUES)
882 return e.value;
883 if (type == KEYS)
884 return e.key;
885 return e;
886 }
887
888 /**
889 * Removes from the backing HashMap the last element which was fetched
890 * with the <code>next()</code> method.
891 * @throws ConcurrentModificationException if the HashMap was modified
892 * @throws IllegalStateException if called when there is no last element
893 */
894 public void remove()
895 {
896 if (knownMod != modCount)
897 throw new ConcurrentModificationException();
898 if (last == null)
899 throw new IllegalStateException();
900
901 HashMap.this.remove(last.key);
902 last = null;
903 knownMod++;
904 }
905 }
906}
Note: See TracBrowser for help on using the repository browser.