Java HashSet vs HashMap

后端 未结 7 1794
长发绾君心
长发绾君心 2020-12-12 16:13

I understand that HashSet is based on HashMap implementation but is used when you need unique set of elements. So why in the next code when putting

7条回答
  •  盖世英雄少女心
    2020-12-12 16:32

    The map holds unique keys. When you invoke put with a key that exists in the map, the object under that key is replaced with the new object. Hence the size 1.

    The difference between the two should be obvious:

    • in a Map you store key-value pairs
    • in a Set you store only the keys

    In fact, a HashSet has a HashMap field, and whenever add(obj) is invoked, the put method is invoked on the underlying map map.put(obj, DUMMY) - where the dummy object is a private static final Object DUMMY = new Object(). So the map is populated with your object as key, and a value that is of no interest.

提交回复
热议问题