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 ?
HashSet can not guarantee insertion order so no point in get method. What are you missing is implementing equals and use contains() which will iterate and find the object.
Sets do not support order, so a replace method would be pointless. In fact it would be difficult to implement for something like HashSet. Using remove() and add() is the correct way to do it.
As java set doesn't provide get method, I need to iterate over the set in my code and update the name when I find the equal object (i.e. when ID matches). If you had get method, this code could have been shortened.
Methods of Set add() - adds the specified element to the set. addAll() - adds all the elements of the specified collection to the set. iterator() - returns an iterator that can be used to access elements of the set sequentially. remove() - removes the specified element from the set.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With