問(wèn)題描述
我有那個(gè)結(jié)構(gòu)的集合.我沒(méi)有重復(fù),但是當(dāng)我打電話時(shí):set.add(element)
-> 并且已經(jīng)有確切的元素我想替換舊的.
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() + " WYSTAPIEN " + 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();
}
}
推薦答案
每次添加前做一個(gè)remove:
Do a remove before each add:
someSet.remove(myObject);
someSet.add(myObject);
remove 將刪除任何等于 myObject 的對(duì)象.或者,您可以檢查添加結(jié)果:
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);
}
哪種方式更有效取決于您發(fā)生碰撞的頻率.如果它們很少見,第二種形式通常只做一次操作,但當(dāng)發(fā)生碰撞時(shí),它會(huì)做三次.第一種形式總是做兩個(gè).
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.
這篇關(guān)于替換 HashSet Java 成員的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!