Currently I have to write the following to update an element already contained in a Set:
Set mySet= ...
Element e1 = new Element (...);
....
....
Element e2 = new Element (...);
\\e1 and e2 are different instances, but equals.
\\update the element contained into the Set
if (mySet.contains(e2)){
mySet.remove(e2);
myset.add(e2);
}
That doesnt look nice. Is there an alternative ?
A Set is a data structure made to avoid duplicate by mean of using equals() on the object; that also means that two object that are equals() to each other are considered to be perfectly equivalent. Ie, whether you use the version already in the Set or the new one, your code should work the same.
If you want to update the object with a new value, then this is clearly not the case for you (the two version can not replace each other), and you should then use another data structure (eg, a Map, where you can easily override the value, in this case, the key can even be the object itself).