java - 如何生成集合的哈希以确保完整性?

标签 java hash set

也许这个问题之前有人问过(我没找到)...

我有一个 aprox 的 java.util.Set。 50000 个字符串。我想生成某种散列来检查它是否已更改(比较 Set 的两个版本的散列)?

如果 Set 发生变化,则哈希必须不同。

如何实现?谢谢!

编辑:
对不起,误导性的措辞。我不想检查“它”是否已更改(同一实例)。相反,我想检查两个数据库查询是否生成两个(可能相同)一组字符串的实例。

最佳答案

我会尝试使用 java.util.AbstractSethashCode 方法,如文档中所述:

Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash code of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of Object.hashCode().

当然,这仅在您的 Set 实现从 AbstractSet 扩展时有效,我想您使用例如java.util.HashSet一如既往地存在哈希冲突的可能性。

或者,您可以扩展现有的 Set 实现并覆盖状态更改方法,如果每个对象的哈希计算变得过于昂贵,这可能有意义,例如:

class ChangeSet<E> extends java.util.HashSet<E> {
    private boolean changed = false;

    @Override
    public boolean add(E e) {
        changed = true;
        super.add(e);
    }

    public void commit() {
        changed = false;
    }

    public boolean isChanged() {
        return changed;
    }

    /* and all the other methods (addAll, remove, removeAll, etc.) */

}

关于java - 如何生成集合的哈希以确保完整性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8723564/

相关文章:

java - 为什么在我的例子中 Spring Boot Actuator 不显示/info,/actuator 端点?

Java spring application.properties 值没有被应用程序使用

Ruby - 使用哈希返回数组中的重复项,这有效吗?

javascript - 在 Firefox 中设置 top.location.hash 为 %20

c# - 封装C#新手

java - 在 Java 中访问和引用 HashMap 时遇到问题

java - Selenium java静默模式

java - Rome : Unable to get full description of post for a feed

hash - 可变 HashMap 键是一种危险的做法吗?

c++ - 在c++标准模板库(STL)中使用set