I have Set of that structure. I do not have duplicates but when I call:
set.add(element)
-> and there is already exact element I would like the old to be replac
Try something as follows (this will only make sense if the equals
and hashCode
depends on one field, but the other fields could have different values):
if(!set.add(obj)) {
//set already contains the element (not the same object though)
set.remove(obj); //remove the one in the set
set.add(obj); //add the new one
}
Check out the documentation for the Set.add method
If this set already contains the element, the call leaves the set unchanged and returns false.