Does adding a duplicate value to a HashSet/HashMap replace the previous value

前端 未结 8 1579
迷失自我
迷失自我 2020-12-02 07:14

Please consider the below piece of code:

HashSet hs = new HashSet();
hs.add(\"hi\"); -- (1)
hs.add(\"hi\"); -- (2)

hs.size() w

8条回答
  •  Happy的楠姐
    2020-12-02 07:30

    You need to check put method in Hash map first as HashSet is backed up by HashMap

    1. When you add duplicate value say a String "One" into HashSet,
    2. An entry ("one", PRESENT) will get inserted into Hashmap(for all the values added into set, the value will be "PRESENT" which if of type Object)
    3. Hashmap adds the entry into Map and returns the value, which is in this case "PRESENT" or null if Entry is not there.
    4. Hashset's add method then returns true if the returned value from Hashmap equals null otherwise false which means an entry already exists...

提交回复
热议问题