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 replaced.
import java.io.*; public class WordInfo implements Serializable { File plik; Integer wystapienia; public WordInfo(File plik, Integer wystapienia) { this.plik = plik; this.wystapienia = wystapienia; } public String toString() { // if (plik.getAbsolutePath().contains("src") && wystapienia != 0) return plik.getAbsolutePath() + "\tWYSTAPIEN " + wystapienia; // return ""; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(!(obj instanceof WordInfo)) return false; return this.plik.equals(((WordInfo) obj).plik); } @Override public int hashCode() { return this.plik.hashCode(); } }
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.
HashSet add() Method in Java add() method in Java HashSet is used to add a specific element into a HashSet. This method will add the element only if the specified element is not present in the HashSet else the function will return False if the element is already present in the HashSet.
Do a remove before each add:
someSet.remove(myObject); someSet.add(myObject);
The remove will remove any object that is equal to myObject. Alternatively, you can check the add result:
if(!someSet.add(myObject)) { someSet.remove(myObject); someSet.add(myObject); }
Which would be more efficient depends on how often you have collisions. If they are rare, the second form will usually do only one operation, but when there is a collision it does three. The first form always does two.
If the set already contains an element that equals()
the element you are trying to add, the new element won't be added and won't replace the existing element. To guarantee that the new element is added, simply remove it from the set first:
set.remove(aWordInfo); set.add(aWordInfo);
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