Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not HashSet.add(Object) replace existing object?

This is more of a design question in which I am curious as to why the HashSet does not support put like operation with the add.

If I want to update an object with equal hashCode as an existing object I have to do this:

hashSet.remove(o);
hasSet.add(o);

I think a

hashSet.add(o);

should have sufficed since it uses a HashMap under the hood anyway.

like image 878
F.O.O Avatar asked Dec 04 '25 21:12

F.O.O


1 Answers

There is no point to replace a HashSet element with an element equal to it. In HashMap there is a point to replace the entry for an existing key, since the value can be different.

I think a hashSet.add(o); should have sufficed since it uses a HashMap under the hood anyway.

Actually no. You are correct that HashSet is backed by a HashMap, where each element of the Set is a key and the value is a dummy object. However, since map.put(key,value) doesn't replace the key if an equal key is present in the Map (it only replaces the value), HashSet cannot replace the element if it already exists in the Set without first removing it.

like image 125
Eran Avatar answered Dec 06 '25 11:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!