How can I have a HashMap with unique keys in java?

前端 未结 6 1947
滥情空心
滥情空心 2021-02-11 13:26

How can I have a HashMap with unique keys in Java? Or even does this make any sense to have unique keys in HashMap or the keys are unique by default? I am a newbie. thx

相关标签:
6条回答
  • 2021-02-11 13:43

    Try to look at the Java API for Map which is interface that HashMap implements. The first sentence is:

    An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

    0 讨论(0)
  • 2021-02-11 13:43

    Hash map key is unique. Add duplicate key, then it will be overwritten.

     HashMap hm = new HashMap();
     hm.put("1", new Integer(1));
     hm.put("2", new Integer(2));
     hm.put("3", new Integer(3));
     hm.put("4", new Integer(4));
     hm.put("1", new Integer(5));// value integer 1 is overwritten by 5
    

    By default Hashmap is not synchronized.

    0 讨论(0)
  • 2021-02-11 13:44

    A generic hashmap is usually implemented as an associative array, so let's say your array has N elements, from 0 to N-1, when you want to add a new (key, value) pair, what it's done behind the scenes is (just conceptually):

    1. index = hash(key) mod N
    2. array[index] = value

    So, by construction, a key is mapped to one and one only array entry.

    Please note that it's actually a bit more complex than this: I am ignoring on purpose things like collision handling, rehashing, etc, you may have a good general idea here https://en.wikipedia.org/wiki/Hash_table

    0 讨论(0)
  • 2021-02-11 13:46

    HashMap is a collection to store (key,value) pairs and According to the documentation of HashMap the keys are always unique.

    If you add a key which already exists(collision) in the hashmap, the old value will be replaced.

    0 讨论(0)
  • HasMap has unique keys. as .keySet() returns Set which has unique members

    0 讨论(0)
  • 2021-02-11 13:55

    The keys are unique in all maps. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.

    0 讨论(0)
提交回复
热议问题