Reprinted from: http://www.cnblogs.com/skywang12345/p/3310835.html
The first part HashMap introduction
Introduction to HashMap
- HashMap is a hash table that stores a key-value map.
- HashMap inherits from AbstractMap and implements Map, Cloneable, and java.io.Serializable interfaces.
- The implementation of HashMap is not synchronized, which means it is not thread safe. Its key and value can be null. Also, the mapping in HashMap is not ordered.
- 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 just the capacity of the hash table when it was created. The load factor is a measure of how full a hash table can get before its capacity automatically increases. 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 (ie, the internal data structure is rebuilt), so that the hash table will have approximately twice the number of buckets.
- Typically, the default load factor is 0.75 , which seeks a compromise between time and space costs. A high load factor reduces space overhead, but also increases query cost (reflected in most HashMap-like operations, including get and put operations). The number of entries required in the map and its load factor should be taken into account when setting the initial capacity in order 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 operation will occur.
HashMap constructor
HashMap() // Constructs an empty HashMap with default initial capacity (16) and default load factor (0.75). HashMap(int capacity) // Constructor specifying "capacity size" HashMap(int capacity, float loadFactor) // Constructor specifying "capacity size" and "load factor" HashMap(Map<? extends K, ? extends V> map) // Constructor with "sub Map"
HashMap API
void clear() //Remove all mappings from Map Object clone() //Returns a shallow copy of this HashMap instance: keys and values themselves are not cloned boolean containsKey(Object key) //If this map contains the mapping relationship of the specified key, return true boolean containsValue(Object value)//Returns true if this map maps one or more keys to the specified value Set<Entry<K, V>> entrySet() //returns the Set view of the maps contained in this map V get(Object key) //Returns the value to which the specified key maps; if this map does not contain a key map, returns null boolean isEmpty() // returns true if this map does not contain a key-value map Set<K> keySet() //Returns a Set view of the keys contained in this map. V put(K key, V value) //Associate the specified value with the key specified in this map void putAll(Map<? extends K, ? extends V> map)//Copy all maps in the specified Map to this Map V remove(Object key) //If it exists, remove the map of the specified key from this map int size() //returns the number of key-value mappings in this map Collection<V> values() //Returns a collection view of the values contained in this map.
The second part HashMap data structure
Inheritance relationship of HashMapjava.lang.Object Java.util.AbstractMap <K, V> ↳ java.util.HashMap <K, V> public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { }
Relationship between HashMap and Map
As can be seen from the figure:
- HashMap inherits from the AbstractMap class and implements the Map interface. Map is a "key-value key-value pair" interface, and AbstractMap implements the general function interface of "key-value pair".
- HashMap is a hash table implemented by the "zipper method". It includes several important member variables: table, size, threshold, loadFactor, modCount
- table: is an Entry[] array type, and Entry is actually a singly linked list. The "key-value pairs" of the hash table are stored in the Entry array.
- size: is the size of the HashMap, which is the number of key-value pairs saved by the HashMap.
- threshold: is the threshold of HashMap, which is used to judge whether the capacity of HashMap needs to be adjusted. The value of threshold = "capacity * load factor", when the number of stored data in HashMap reaches the threshold, the capacity of HashMap needs to be doubled. loadFactor: is the load factor.
- modCount: is used to implement the fail-fast mechanism.
The third part HashMap traversal method
1. Traverse the key-value pairs of HashMap
Step 1: Obtain the Set collection of "key-value pairs" of HashMap according to entrySet().Step 2: Traverse the collection obtained by "Step 1" through the Iterator iterator.
// Assume map is a HashMap object // The key in the map is of type String, and the value is of type Integer Integer integer = null; Iterator iter = map.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); // get key key = (String)entry.getKey(); // get value integ = (Integer)entry.getValue(); }
2. Traverse the keys of the HashMap
Step 1: Get the collection of "values" of HashMap according to value().Step 2: Traverse the collection obtained by "Step 1" through the Iterator iterator.
// Assume map is a HashMap object // The key in the map is of type String, and the value is of type Integer Integer value = null; Collection c = map.values(); Iterator iter= c.iterator(); while (iter.hasNext()) { value = (Integer)iter.next(); }
3. Walk through the test program
import java.util.Map; import java.util.Random; import java.util.Iterator; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Collection; /* * @desc A test program that traverses the HashMap. * (1) Traverse key and value through entrySet(), refer to the implementation function: * iteratorHashMapByEntryset() * (2) Traverse key and value through keySet(), refer to the implementation function: * iteratorHashMapByKeyset() * (3) To traverse the value through values(), refer to the implementation function: * iteratorHashMapJustValues() * * @author skywang */ public class HashMapIteratorTest { public static void main(String[] args) { int val = 0; String key = null; Integer value = null; Random r = new Random(); HashMap map = new HashMap(); for (int i=0; i<12; i++) { // Get a random number between [0,100) val = r.nextInt(100); key = String.valueOf(val); value = r.nextInt(5); // add to HashMap map.put(key, value); System.out.println(" key:"+key+" value:"+value); } // Traverse the key-value of HashMap through entrySet() iteratorHashMapByEntryset(map) ; // Traverse the key-value of HashMap through keySet() iteratorHashMapByKeyset(map) ; // Just traverse the value of HashMap iteratorHashMapJustValues(map); } /* * Traverse HashMap through entry set * efficient! */ private static void iteratorHashMapByEntryset(HashMap map) { if (map == null) return ; System.out.println("\niterator HashMap By entryset"); String key = null; Integer integ = null; Iterator iter = map.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); key = (String)entry.getKey(); integ = (Integer)entry.getValue(); System.out.println(key+" -- "+integ.intValue()); } } /* * Traverse HashMap through keyset * low efficiency! */ private static void iteratorHashMapByKeyset(HashMap map) { if (map == null) return ; System.out.println("\niterator HashMap By keyset"); String key = null; Integer integ = null; Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { key = (String)iter.next(); integ = (Integer)map.get(key); System.out.println(key+" -- "+integ.intValue()); } } /* * Traverse the values of HashMap */ private static void iteratorHashMapJustValues(HashMap map) { if (map == null) return ; Collection c = map.values(); Iterator iter= c.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }
Part IV HashMap Example
import java.util.Map; import java.util.Random; import java.util.Iterator; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Collection; /* * @desc HashMap test program * * @author skywang */ public class HashMapTest { public static void main(String[] args) { testHashMapAPIs(); } private static void testHashMapAPIs() { // initialize random seed Random r = new Random(); // Create a new HashMap HashMap map = new HashMap(); // add action map.put("one", r.nextInt(10)); map.put("two", r.nextInt(10)); map.put("three", r.nextInt(10)); // print out the map System.out.println("map:"+map ); // Traverse key-value through Iterator Iterator iter = map.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); System.out.println("next : "+ entry.getKey() +" - "+entry.getValue()); } // Number of key-value pairs in HashMap System.out.println("size:"+map.size()); // containsKey(Object key) : Whether to contain the key key System.out.println("contains key two : "+map.containsKey("two")); System.out.println("contains key five : "+map.containsKey("five")); // containsValue(Object value) : Whether to contain the value value System.out.println("contains value 0 : "+map.containsValue(new Integer(0))); // remove(Object key) : delete the key-value pair corresponding to the key key map.remove("three"); System.out.println("map:"+map ); // clear() : clear the HashMap map.clear(); // isEmpty() : Whether the HashMap is empty System.out.println((map.isEmpty()?"map is empty":"map is not empty") ); } }
The result of running it once is as follows:
map:{two=7, one=9, three=6} next : two - 7 next : one - 9 next : three - 6 size:3 contains key two : true contains key five : false contains value 0 : false map:{two=7, one=9} map is empty