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

前端 未结 6 657
长发绾君心
长发绾君心 2021-02-11 13:36

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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-11 14:01

    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

提交回复
热议问题