Possible Duplicate:
Java - HashMap vs Map objects
does the hash-map have multiple values?
A hash map is a particular implementation of a map, using a hash function. Maps always have (up to) one value per key.
In Java, a Map is an interface whereas a HashMap implements the Map interface. In other words, a HashMap can be instantiated and assigned to a Map variable
Map myMap = new HashMap();
A HashMap and a Map can contain multiple key/value pairs, but they cannot contain duplicate keys.
With reference to Java language, Map is an interface in java.util package that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. HashMap is a Hash table based implementation of the Map interface. HashMap provides all of the optional map operations, and permits null values and the null key. If you want to use multiple values for a single key, then just use either a Map<K, Collection> or Google Collections MultiMap<K, V>. In case the key is a String, hash map will create a hash of the string and use that hash to index an array, giving constant lookup. However, there would be some collision detection required as the hash of a string can produce the same index as the hash of another string. Therefore complexity is added to manage collisions.
Map:
- Cannot contain duplicate values.
- Each key can map to atmost one value.
HashMap:
- Hash creation (might be linear complexity to string size depending on algorithm to create hash).
- Constant lookup with hash.
- If Collision taken into consideration, adds up linear complexity to number of collisions for the same hash.
精彩评论