java - 枚举值的 hashCode() 返回值是否随运行时变化

标签 java hashcode

我在我的一个对象(A 实例)中使用重写的 hashCode() 来为该对象生成唯一的整数 ID。唯一性仅取决于 ArrayList (I) 中的元素(B 的实例)。

以下是I的定义:

public class I extends ArrayList<B> {
    //object of this class will iterate over this array
    private B[] arrayOfB;

    //other methods and variable to do something
    ...
}

B的定义

public class B {
    private SomeEnum type;
    private Object   value; //this can be Integer, String, or some object defined by me

    //getters for both private variables
    ...
}

A的定义

public class C implements Iterable {
    private I myIterable;

    @Override
    public int hashCode() {
        int result = 17;
        for(B b: myIterable) {
            result = 31 * result + b.getType().hashCode();
            result = 31 * result + b.getValue().hashCode();
        }
        return result;
    }

    //other methods for this class
    ...
}

如您所见,我迭代了 myIterable 中的所有对象并构造了最终的哈希。结果取决于 myIterable 中每个 b 中包含的 typevalue。我注意到,这个值随着程序运行的不同而变化,这会产生一个问题,因为程序正在创建重复对象。

我可以为相关枚举实现 hashCode(),但我想知道是否有其他方法来处理这个问题。以下是我的问题:

  • 相等字符串的 hashCode() 可以在运行时改变吗?
  • 相同枚举值的 hashCode() 可以在运行时改变吗?

注意:我知道我的 A.hashCode() 实现将根据 myIterableb 的顺序返回不同的哈希值>,这是不希望的。我正在修复它,以便顺序不再重要。

最佳答案

那么无论顺序如何,您是否都会得到不同的结果(例如,当这些 hashCode 单独计算时)? 来自 hashCode 文档 http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29 :

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

理论上是可以的。但是,我认为这将是非标准实现。这是实际的源代码(openjdk7):

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/String.java#String.hashCode%28%29

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Enum.java#Enum.hashCode%28%29

关于java - 枚举值的 hashCode() 返回值是否随运行时变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661271/

相关文章:

java - 如何从 onchange 事件调用 Controller 方法?

data-structures - 函数的哈希码在原子内部发生变化......为什么会发生这种情况?

c# - 如何在 C# 中从源代码创建哈希码?

hadoop - 计算HDFS中的HashCode函数

java - JVM 1.6 版将创建多少个字符串对象

java - WebView下载管理器: How to download files with their default names?

java - int.class.isInstance(Object) 是矛盾的吗?

java - 如何在运行时动态地将外部 jar 文件添加到类路径中?

Java Set of Maps hashCode 不正确?

python - 如何在Python中定义哈希函数