Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
What issues / pitfalls must be considered when overriding equals and hashCode?
I want to create a large HashMap but the put() performance is not good enough. Any ideas? Other data structure suggestions are welcome but I need the lookup feature of a Java Map: map.get(key) In my case I want to create a map with 26 million entries. Using the standard Java HashMap the put rate becomes unbearably slow after 2-3 million insertions. Also, does anyone know if using different...
I may be teaching a "Java crash-course" soon. While it is probably safe to assume that the audience members will know Big-O notation, it is probably not safe to assume that they will know what the order of the various operations on various collection implementations is. I could take time to generate a summary matrix myself, but if it's already out there in the public domain somewhere, I'd sur...
Does MATLAB have any support for hash tables? Some background I am working on a problem in Matlab that requires a scale-space representation of an image. To do this I create a 2-D Gaussian filter with variance sigma*s^k for k in some range., and then I use each one in turn to filter the image. Now, I want some sort of mapping from k to the filtered image. If k were always an integer, I'd ...
How to create and fetch associative array in Java, like this in php $arr[0]['name'] = 'demo'; $arr[0]['fname'] = 'fdemo'; $arr[1]['name'] = 'test'; $arr[1]['fname'] = 'fname';
Hey guys, I know this is a rather trivial question, but what is the best way handle this situation? I have several cases and I am just using simple if, if elses. I remember using a look up table at one point and I drew one out on paper, but I am not sure how to implement it in Java. Any tips would be appreciated, even if the answer is that my way is just fine. private int transition(char curr...
What is the difference between the following maps I create (in another question, people answered using them seemingly interchangeably and I'm wondering if/how they are different): HashMap<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
I need to store key/value info in some type of collection. In C#, I'd define a dictionary like this: var entries = new Dictionary<string, int>(); entries.Add("Stop me", 11); entries.Add("Feed me", 12); entries.Add("Walk me", 13); Then I would access the values so: int value = entries["Stop me"]; How do I do this in Java? I've seen examples with ArrayList, but I'd like the solution...
What values should I pass to create an efficient HashMap / HashMap based structures for N items? In an ArrayList, the efficient number is N (N already assumes future grow). What should be the parameters for a HashMap? ((int)(N * 0.75d), 0.75d)? more? less? What is the effect of changing the load factor?
Given the following code, with two alternative ways to iterate through it, is there any performance difference between these two methods? Map<String, Integer> map = new HashMap<String, Integer>(); //populate map //alt. #1 for (String key : map.keySet()) { Integer value = map.get(key); //use key and value } ...
Is there a theoretical limit for the number of key entries that can be stored in a HashMap or does it purely depend on the heap memory available? Also, which data structure is the best to store a very large number of objects (say several hundred thousand objects)?
I've coded a method something like this... But I guess this should undergo refactoring. Can any one suggest the best approach to avoid using this multiple if statements? private String getMimeType(String fileName){ if(fileName == null) { return ""; } if(fileName.endsWith(".pdf")) { return "application/pdf"; } if(fileName.endsWith(".doc")) { return "application/msword"; } i...
I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java: Array ( ["col_name_1"] => Array ( 1 => ["col_value_1"], 2 => ["col_value_2"], ... , n => ["co...
I have a requirement to present highly structured information picked from a highly un-structured web service. In order to display the info correctly, I have to do a lot of String matches and duplicate removals to ensure I'm picking the right combination of elements. One of my challenges involves determining if a String is in an Array of Strings. My dream is to do "searchString.isIn(stringArr...
What is the difference between a Hashtable and Properties?
I'm writing a debugger for a Z80-emulator we are writing in a school project, using Java. The debugger reads a command from the user, executes it, reads another command, etc. Commands can either be argument less, have optional arguments, or take an unlimited amount of arguments. Arguments are mostly integers, but occasionally they're strings. Currently, we're using the Scanner-class for read...
Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used?
Is static initialized unmodifiableCollection.get guaranteed immutable? For: static final Map FOO = Collections.unmodifiableMap(new HashMap()); Can multiple threads use method get and not run into problems? Even through items in FOO cannot be added/removed, what's stopping the get method from manipulating FOO's internal state for caching purposes, etc. If the internal state is modified in ...
I'm writing (well, completing) an "extension" of Java which will help role programming. I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer: MyClass extends String implements ObjectWithRoles { //implements... is added /*Added by me */ public setRole(...){...} public ... /*Ends of stuff added*/ ....
Map m1 = new HashMap(); m1.put("map", "HashMap"); m1.put("schildt", "java2"); m1.put("mathew", "Hyden"); m1.put("schildt", "java2s"); print(m1.keySet()); print(m1.values()); SortedMap sm = new TreeMap(); sm.put("map", "TreeMap"); sm.put("schildt", "java2"); sm.put("mathew", "Hyden"); sm.put("schildt", "java2s"); print(sm.keySet()); pri...
Ok so here is my issue. I have to HashSet's, I use the Removeall method to delete values that exist in one set from the other. Prior to calling the method, I obviously add the values to the Sets. I call .toUpperCase() on each String before adding because the values are of different cases in both lists. There is no rhyme or reason to the case. Once I call RemoveAll, I need to have the origina...
   /*
    * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.util;
  import java.io.*;

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   Map m = Collections.synchronizedMap(new HashMap(...));

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Parameters:
<K> the type of keys maintained by this map
<V> the type of mapped values
Author(s):
Doug Lea
Josh Bloch
Arthur van Hoff
Neal Gafter
Since:
1.2
See also:
java.lang.Object.hashCode()
Collection
Map
TreeMap
Hashtable
 
 
 public class HashMap<K,V>
     extends AbstractMap<K,V>
     implements Map<K,V>, CloneableSerializable
 {

    
The default initial capacity - MUST be a power of two.
 
     static final int DEFAULT_INITIAL_CAPACITY = 16;

    
The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments. MUST be a power of two <= 1<<30.
 
     static final int MAXIMUM_CAPACITY = 1 << 30;

    
The load factor used when none specified in constructor.
 
     static final float DEFAULT_LOAD_FACTOR = 0.75f;

    
The table, resized as necessary. Length MUST Always be a power of two.
 
     transient Entry[] table;

    
The number of key-value mappings contained in this map.
 
     transient int size;

    
The next size value at which to resize (capacity * load factor).

Serial:
 
     int threshold;

    
The load factor for the hash table.

Serial:
 
     final float loadFactor;

    
The number of times this HashMap has been structurally modified Structural modifications are those that change the number of mappings in the HashMap or otherwise modify its internal structure (e.g., rehash). This field is used to make iterators on Collection-views of the HashMap fail-fast. (See ConcurrentModificationException).
 
     transient volatile int modCount;

    
Constructs an empty HashMap with the specified initial capacity and load factor.

Parameters:
initialCapacity the initial capacity
loadFactor the load factor
Throws:
java.lang.IllegalArgumentException if the initial capacity is negative or the load factor is nonpositive
 
     public HashMap(int initialCapacityfloat loadFactor) {
         if (initialCapacity < 0)
             throw new IllegalArgumentException("Illegal initial capacity: " +
                                                initialCapacity);
         if (initialCapacity > )
             initialCapacity = ;
         if (loadFactor <= 0 || Float.isNaN(loadFactor))
             throw new IllegalArgumentException("Illegal load factor: " +
                                                loadFactor);
 
         // Find a power of 2 >= initialCapacity
         int capacity = 1;
         while (capacity < initialCapacity)
             capacity <<= 1;
 
         this. = loadFactor;
          = (int)(capacity * loadFactor);
          = new Entry[capacity];
         init();
     }

    
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

Parameters:
initialCapacity the initial capacity.
Throws:
java.lang.IllegalArgumentException if the initial capacity is negative.
 
     public HashMap(int initialCapacity) {
         this(initialCapacity);
     }

    
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
 
     public HashMap() {
         this. = ;
          = new Entry[];
         init();
     }

    
Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.

Parameters:
m the map whose mappings are to be placed in this map
Throws:
java.lang.NullPointerException if the specified map is null
 
     public HashMap(Map<? extends K, ? extends V> m) {
         this(Math.max((int) (m.size() / ) + 1,
                       ), );
         putAllForCreate(m);
     }
 
     // internal utilities
 
    
Initialization hook for subclasses. This method is called in all constructors and pseudo-constructors (clone, readObject) after HashMap has been initialized but before any entries have been inserted. (In the absence of this method, readObject would require explicit knowledge of subclasses.)
 
     void init() {
     }

    
Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical because HashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower bits. Note: Null keys always map to hash 0, thus index 0.
 
     static int hash(int h) {
         // This function ensures that hashCodes that differ only by
         // constant multiples at each bit position have a bounded
         // number of collisions (approximately 8 at default load factor).
         h ^= (h >>> 20) ^ (h >>> 12);
         return h ^ (h >>> 7) ^ (h >>> 4);
     }

    
Returns index for hash code h.
 
     static int indexFor(int hint length) {
         return h & (length-1);
     }

    
Returns the number of key-value mappings in this map.

Returns:
the number of key-value mappings in this map
 
     public int size() {
         return ;
     }

    
Returns true if this map contains no key-value mappings.

Returns:
true if this map contains no key-value mappings
 
     public boolean isEmpty() {
         return  == 0;
     }

    
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

 
     public V get(Object key) {
         if (key == null)
             return getForNullKey();
         int hash = hash(key.hashCode());
         for (Entry<K,V> e = [indexFor(hash.)];
              e != null;
              e = e.next) {
             Object k;
             if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                 return e.value;
         }
         return null;
     }

    
Offloaded version of get() to look up null keys. Null keys map to index 0. This null case is split out into separate methods for the sake of performance in the two most commonly used operations (get and put), but incorporated with conditionals in others.
 
     private V getForNullKey() {
         for (Entry<K,V> e = [0]; e != nulle = e.next) {
             if (e.key == null)
                 return e.value;
         }
         return null;
     }

    
Returns true if this map contains a mapping for the specified key.

Parameters:
key The key whose presence in this map is to be tested
Returns:
true if this map contains a mapping for the specified key.
 
     public boolean containsKey(Object key) {
         return getEntry(key) != null;
     }

    
Returns the entry associated with the specified key in the HashMap. Returns null if the HashMap contains no mapping for the key.
 
     final Entry<K,V> getEntry(Object key) {
         int hash = (key == null) ? 0 : hash(key.hashCode());
         for (Entry<K,V> e = [indexFor(hash.)];
              e != null;
              e = e.next) {
             Object k;
             if (e.hash == hash &&
                 ((k = e.key) == key || (key != null && key.equals(k))))
                 return e;
         }
         return null;
     }


    
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Parameters:
key key with which the specified value is to be associated
value value to be associated with the specified key
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
 
     public V put(K key, V value) {
         if (key == null)
             return putForNullKey(value);
         int hash = hash(key.hashCode());
         int i = indexFor(hash.);
         for (Entry<K,V> e = [i]; e != nulle = e.next) {
             Object k;
             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                 V oldValue = e.value;
                 e.value = value;
                 e.recordAccess(this);
                 return oldValue;
             }
         }
 
         ++;
         addEntry(hashkeyvaluei);
         return null;
     }

    
Offloaded version of put for null keys
 
     private V putForNullKey(V value) {
         for (Entry<K,V> e = [0]; e != nulle = e.next) {
             if (e.key == null) {
                 V oldValue = e.value;
                 e.value = value;
                 e.recordAccess(this);
                 return oldValue;
             }
         }
         ++;
         addEntry(0, nullvalue, 0);
         return null;
     }

    
This method is used instead of put by constructors and pseudoconstructors (clone, readObject). It does not resize the table, check for comodification, etc. It calls createEntry rather than addEntry.
 
     private void putForCreate(K key, V value) {
         int hash = (key == null) ? 0 : hash(key.hashCode());
         int i = indexFor(hash.);

        
Look for preexisting entry for key. This will never happen for clone or deserialize. It will only happen for construction if the input Map is a sorted map whose ordering is inconsistent w/ equals.
 
         for (Entry<K,V> e = [i]; e != nulle = e.next) {
             Object k;
             if (e.hash == hash &&
                 ((k = e.key) == key || (key != null && key.equals(k)))) {
                 e.value = value;
                 return;
             }
         }
 
         createEntry(hashkeyvaluei);
     }
 
     private void putAllForCreate(Map<? extends K, ? extends V> m) {
         for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
             Map.Entry<? extends K, ? extends V> e = i.next();
             putForCreate(e.getKey(), e.getValue());
         }
     }

    
Rehashes the contents of this map into a new array with a larger capacity. This method is called automatically when the number of keys in this map reaches its threshold. If current capacity is MAXIMUM_CAPACITY, this method does not resize the map, but sets threshold to Integer.MAX_VALUE. This has the effect of preventing future calls.

Parameters:
newCapacity the new capacity, MUST be a power of two; must be greater than current capacity unless current capacity is MAXIMUM_CAPACITY (in which case value is irrelevant).
 
     void resize(int newCapacity) {
         Entry[] oldTable = ;
         int oldCapacity = oldTable.length;
         if (oldCapacity == ) {
              = .;
             return;
         }
 
         Entry[] newTable = new Entry[newCapacity];
         transfer(newTable);
          = newTable;
          = (int)(newCapacity * );
     }

    
Transfers all entries from current table to newTable.
 
     void transfer(Entry[] newTable) {
         Entry[] src = ;
         int newCapacity = newTable.length;
         for (int j = 0; j < src.lengthj++) {
             Entry<K,V> e = src[j];
             if (e != null) {
                 src[j] = null;
                 do {
                     Entry<K,V> next = e.next;
                     int i = indexFor(e.hashnewCapacity);
                     e.next = newTable[i];
                     newTable[i] = e;
                     e = next;
                 } while (e != null);
             }
         }
     }

    
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.

Parameters:
m mappings to be stored in this map
Throws:
java.lang.NullPointerException if the specified map is null
 
     public void putAll(Map<? extends K, ? extends V> m) {
         int numKeysToBeAdded = m.size();
         if (numKeysToBeAdded == 0)
             return;
 
         /*
          * Expand the map if the map if the number of mappings to be added
          * is greater than or equal to threshold.  This is conservative; the
          * obvious condition is (m.size() + size) >= threshold, but this
          * condition could result in a map with twice the appropriate capacity,
          * if the keys to be added overlap with the keys already in this map.
          * By using the conservative calculation, we subject ourself
          * to at most one extra resize.
          */
         if (numKeysToBeAdded > ) {
             int targetCapacity = (int)(numKeysToBeAdded /  + 1);
             if (targetCapacity > )
                 targetCapacity = ;
             int newCapacity = .;
             while (newCapacity < targetCapacity)
                 newCapacity <<= 1;
             if (newCapacity > .)
                 resize(newCapacity);
         }
 
         for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
             Map.Entry<? extends K, ? extends V> e = i.next();
             put(e.getKey(), e.getValue());
         }
     }

    
Removes the mapping for the specified key from this map if present.

Parameters:
key key whose mapping is to be removed from the map
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
 
     public V remove(Object key) {
         Entry<K,V> e = removeEntryForKey(key);
         return (e == null ? null : e.value);
     }

    
Removes and returns the entry associated with the specified key in the HashMap. Returns null if the HashMap contains no mapping for this key.
 
     final Entry<K,V> removeEntryForKey(Object key) {
         int hash = (key == null) ? 0 : hash(key.hashCode());
         int i = indexFor(hash.);
         Entry<K,V> prev = [i];
         Entry<K,V> e = prev;
 
         while (e != null) {
             Entry<K,V> next = e.next;
             Object k;
             if (e.hash == hash &&
                 ((k = e.key) == key || (key != null && key.equals(k)))) {
                 ++;
                 --;
                 if (prev == e)
                     [i] = next;
                 else
                     prev.next = next;
                 e.recordRemoval(this);
                 return e;
             }
             prev = e;
             e = next;
         }
 
         return e;
     }

    
Special version of remove for EntrySet.
 
     final Entry<K,V> removeMapping(Object o) {
         if (!(o instanceof Map.Entry))
             return null;
 
         Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
         Object key = entry.getKey();
         int hash = (key == null) ? 0 : hash(key.hashCode());
         int i = indexFor(hash.);
         Entry<K,V> prev = [i];
         Entry<K,V> e = prev;
 
         while (e != null) {
             Entry<K,V> next = e.next;
             if (e.hash == hash && e.equals(entry)) {
                 ++;
                 --;
                 if (prev == e)
                     [i] = next;
                 else
                     prev.next = next;
                 e.recordRemoval(this);
                 return e;
             }
             prev = e;
             e = next;
         }
 
         return e;
     }

    
Removes all of the mappings from this map. The map will be empty after this call returns.
 
     public void clear() {
         ++;
         Entry[] tab = ;
         for (int i = 0; i < tab.lengthi++)
             tab[i] = null;
          = 0;
     }

    
Returns true if this map maps one or more keys to the specified value.

Parameters:
value value whose presence in this map is to be tested
Returns:
true if this map maps one or more keys to the specified value
 
     public boolean containsValue(Object value) {
         if (value == null)
             return containsNullValue();
 
         Entry[] tab = ;
         for (int i = 0; i < tab.length ; i++)
             for (Entry e = tab[i] ; e != null ; e = e.next)
                 if (value.equals(e.value))
                     return true;
         return false;
     }

    
Special-case code for containsValue with null argument
 
     private boolean containsNullValue() {
         Entry[] tab = ;
         for (int i = 0; i < tab.length ; i++)
             for (Entry e = tab[i] ; e != null ; e = e.next)
                 if (e.value == null)
                     return true;
         return false;
     }

    
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

Returns:
a shallow copy of this map
 
     public Object clone() {
         HashMap<K,V> result = null;
         try {
             result = (HashMap<K,V>)super.clone();
         } catch (CloneNotSupportedException e) {
             // assert false;
         }
         result.table = new Entry[.];
         result.entrySet = null;
         result.modCount = 0;
         result.size = 0;
         result.init();
         result.putAllForCreate(this);
 
         return result;
     }
 
     static class Entry<K,V> implements Map.Entry<K,V> {
         final K key;
         V value;
         Entry<K,V> next;
         final int hash;

        
Creates new entry.
 
         Entry(int h, K k, V vEntry<K,V> n) {
              = v;
              = n;
              = k;
              = h;
         }
 
         public final K getKey() {
             return ;
         }
 
         public final V getValue() {
             return ;
         }
 
         public final V setValue(V newValue) {
             V oldValue = ;
              = newValue;
             return oldValue;
         }
 
         public final boolean equals(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry e = (Map.Entry)o;
             Object k1 = getKey();
             Object k2 = e.getKey();
             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                 Object v1 = getValue();
                 Object v2 = e.getValue();
                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
                     return true;
             }
             return false;
         }
 
         public final int hashCode() {
             return (==null   ? 0 : .hashCode()) ^
                    (==null ? 0 : .hashCode());
         }
 
         public final String toString() {
             return getKey() + "=" + getValue();
         }

        
This method is invoked whenever the value in an entry is overwritten by an invocation of put(k,v) for a key k that's already in the HashMap.
 
         void recordAccess(HashMap<K,V> m) {
         }

        
This method is invoked whenever the entry is removed from the table.
 
         void recordRemoval(HashMap<K,V> m) {
         }
     }

    
Adds a new entry with the specified key, value and hash code to the specified bucket. It is the responsibility of this method to resize the table if appropriate. Subclass overrides this to alter the behavior of put method.
 
     void addEntry(int hash, K key, V valueint bucketIndex) {
         Entry<K,V> e = [bucketIndex];
         [bucketIndex] = new Entry<K,V>(hashkeyvaluee);
         if (++ >= )
             resize(2 * .);
     }

    
Like addEntry except that this version is used when creating entries as part of Map construction or "pseudo-construction" (cloning, deserialization). This version needn't worry about resizing the table. Subclass overrides this to alter the behavior of HashMap(Map), clone, and readObject.
 
     void createEntry(int hash, K key, V valueint bucketIndex) {
         Entry<K,V> e = [bucketIndex];
         [bucketIndex] = new Entry<K,V>(hashkeyvaluee);
         ++;
     }
 
     private abstract class HashIterator<E> implements Iterator<E> {
         Entry<K,V> next;        // next entry to return
         int expectedModCount;   // For fast-fail
         int index;              // current slot
         Entry<K,V> current;     // current entry
 
         HashIterator() {
              = ;
             if ( > 0) { // advance to first entry
                 Entry[] t = ;
                 while ( < t.length && ( = t[++]) == null)
                     ;
             }
         }
 
         public final boolean hasNext() {
             return  != null;
         }
 
         final Entry<K,V> nextEntry() {
             if ( != )
                 throw new ConcurrentModificationException();
             Entry<K,V> e = ;
             if (e == null)
                 throw new NoSuchElementException();
 
             if (( = e.next) == null) {
                 Entry[] t = ;
                 while ( < t.length && ( = t[++]) == null)
                     ;
             }
              = e;
             return e;
         }
 
         public void remove() {
             if ( == null)
                 throw new IllegalStateException();
             if ( != )
                 throw new ConcurrentModificationException();
             Object k = .;
              = null;
             HashMap.this.removeEntryForKey(k);
              = ;
         }
 
     }
 
     private final class ValueIterator extends HashIterator<V> {
         public V next() {
             return nextEntry().;
         }
     }
 
     private final class KeyIterator extends HashIterator<K> {
         public K next() {
             return nextEntry().getKey();
         }
     }
 
     private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
         public Map.Entry<K,V> next() {
             return nextEntry();
         }
     }
 
     // Subclass overrides these to alter behavior of views' iterator() method
     Iterator<K> newKeyIterator()   {
         return new KeyIterator();
     }
     Iterator<V> newValueIterator()   {
         return new ValueIterator();
     }
     Iterator<Map.Entry<K,V>> newEntryIterator()   {
         return new EntryIterator();
     }
 
 
     // Views
 
     private transient Set<Map.Entry<K,V>> entrySet = null;

    
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
 
     public Set<K> keySet() {
         Set<K> ks = ;
         return (ks != null ? ks : ( = new KeySet()));
     }
 
     private final class KeySet extends AbstractSet<K> {
         public Iterator<K> iterator() {
             return newKeyIterator();
         }
         public int size() {
             return ;
         }
         public boolean contains(Object o) {
             return containsKey(o);
         }
         public boolean remove(Object o) {
             return HashMap.this.removeEntryForKey(o) != null;
         }
         public void clear() {
             HashMap.this.clear();
         }
     }

    
Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
 
     public Collection<V> values() {
         Collection<V> vs = ;
         return (vs != null ? vs : ( = new Values()));
     }
 
     private final class Values extends AbstractCollection<V> {
         public Iterator<V> iterator() {
             return newValueIterator();
         }
         public int size() {
             return ;
         }
         public boolean contains(Object o) {
             return containsValue(o);
         }
         public void clear() {
             HashMap.this.clear();
         }
     }

    
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Returns:
a set view of the mappings contained in this map
 
     public Set<Map.Entry<K,V>> entrySet() {
         return entrySet0();
     }
 
     private Set<Map.Entry<K,V>> entrySet0() {
         Set<Map.Entry<K,V>> es = ;
         return es != null ? es : ( = new EntrySet());
     }
 
     private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
         public Iterator<Map.Entry<K,V>> iterator() {
             return newEntryIterator();
         }
         public boolean contains(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry<K,V> e = (Map.Entry<K,V>) o;
             Entry<K,V> candidate = getEntry(e.getKey());
             return candidate != null && candidate.equals(e);
         }
         public boolean remove(Object o) {
             return removeMapping(o) != null;
         }
         public int size() {
             return ;
         }
         public void clear() {
             HashMap.this.clear();
         }
     }

    
Save the state of the HashMap instance to a stream (i.e., serialize it).

SerialData:
The capacity of the HashMap (the length of the bucket array) is emitted (int), followed by the size (an int, the number of key-value mappings), followed by the key (Object) and value (Object) for each key-value mapping. The key-value mappings are emitted in no particular order.
 
     private void writeObject(java.io.ObjectOutputStream s)
         throws IOException
    {
        Iterator<Map.Entry<K,V>> i =
            ( > 0) ? entrySet0().iterator() : null;
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        // Write out number of buckets
        s.writeInt(.);
        // Write out size (number of Mappings)
        s.writeInt();
        // Write out keys and values (alternating)
        if (i != null) {
            while (i.hasNext()) {
                Map.Entry<K,V> e = i.next();
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }
    private static final long serialVersionUID = 362498820763181265L;

    
Reconstitute the HashMap instance from a stream (i.e., deserialize it).
    private void readObject(java.io.ObjectInputStream s)
         throws IOExceptionClassNotFoundException
    {
        // Read in the threshold, loadfactor, and any hidden stuff
        s.defaultReadObject();
        // Read in number of buckets and allocate the bucket array;
        int numBuckets = s.readInt();
         = new Entry[numBuckets];
        init();  // Give subclass a chance to do its thing.
        // Read in size (number of Mappings)
        int size = s.readInt();
        // Read the keys and values, and put the mappings in the HashMap
        for (int i=0; i<sizei++) {
            K key = (K) s.readObject();
            V value = (V) s.readObject();
            putForCreate(keyvalue);
        }
    }
    // These methods are used when serializing HashSets
    int   capacity()     { return .; }
    float loadFactor()   { return ;   }
New to GrepCode? Check out our FAQ X