替换 HashSet Java 成员

时间:2023-02-25
本文介绍了替换 HashSet Java 成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有那个结构的集合.我没有重复,但是当我打电话时:set.add(element) -> 并且已经有确切的元素我想替换旧的.

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();
    }
}

推荐答案

每次添加前做一个remove:

Do a remove before each add:

 someSet.remove(myObject);
 someSet.add(myObject);

remove 将删除任何等于 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.

这篇关于替换 HashSet Java 成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:已排序的 java 数组中的重复项 下一篇:自动重构工具来查找类似的 Java/Javascript 重复源代

相关文章

最新文章