Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a HashSet Java member

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();     } } 
like image 526
Yoda Avatar asked Nov 19 '12 04:11

Yoda


People also ask

Can we replace a value in Set in Java?

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.

How do you add a character to a HashSet in Java?

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.


2 Answers

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.

like image 122
Patricia Shanahan Avatar answered Oct 12 '22 22:10

Patricia Shanahan


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); 
like image 32
Ted Hopp Avatar answered Oct 12 '22 23:10

Ted Hopp