开发者

What's the difference between hash-map and map [duplicate]

开发者 https://www.devze.com 2023-02-01 20:44 出处:网络
This question already has answers here: 开发者_如何转开发 Closed 12 years ago. Possible Duplicate:
This question already has answers here: 开发者_如何转开发 Closed 12 years ago.

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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号