有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不同的枚举哈希代码生成?

为什么每次运行java main时都有不同的hashCode值? 查看下面的示例代码

interface testInt{

    public int getValue();
}

enum test  implements testInt{
    A( 1 ),
    B( 2 );

    private int value;

    private test( int value ) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

每次你跑步

public static void main( String[] args ) {
     System.out.println( test.A.hashCode() );
}

控制台上将有不同的打印值。 为什么不一致


共 (5) 个答案

  1. # 2 楼答案

    Enum.hashCode没有定义为返回任何特定的值(除了遵守Object.hashCode的规则之外),并且通用实现没有做任何特殊的事情

    为什么??如果您在HashSet中使用枚举(仅)或作为HashMap中的键,那么您应该使用优化的EnumSetEnumMap。现在考虑EnUM是否与其他类型一起使用在^ {CD3}}中。也许您有一些“标准选项”来实现一个接口,但是其他人可以提供他们自己的选项。任何无状态的东西都可以。一个HashSet中有多个枚举类型。如果Enum对散列值使用了序数,那么将出现常见冲突。使用System.identityHashCode以稳健的方式减少冲突

    public interface Option {
    }
    public enum StandardOptions implements Option {
        A, B, C
    }
    enum CustomOptions {
        P, Q, R
    }
    enum MoreOptions {
        X, Y, Z
    }
    
        Set<Option> options = new HashSet<>();
        options.add(A);
        options.add(P);
        options.add(X);
    

    我们真的不想要A.hashCode() == P.hashCode() == X.hashCode()

  2. # 3 楼答案

    也许一些JVM实现基本上返回了^{}(这也会使hashCode变得很棒),但它不会有效地改变任何东西hashCode()值不必在执行或JVM之间保持一致。唯一需要的契约在^{}的JavaDocs中描述,在Object中使用的是enum中的实现

    还要注意,实现接口与hashCode()无关:

    public class TestEnum {
    
        public static void main(String[] args) {
            System.out.println(Silly.B.hashCode());
            System.out.println(Silly.C.hashCode());
            System.out.println(Silly.D.hashCode());
        }
    }
    
    enum Silly {
        B, C, D
    }
    

    这个程序在每次运行时也返回不同的hashCode()

  3. # 4 楼答案

    javadocs清楚地说明了这一点。从javadocs获取对象c中的哈希代码方法 阶级

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

    因此,在演示代码的不同运行过程中,内部地址可能会有所不同,因此您看到不同的值是完全正常的

    根据需要,如果希望hashcode()方法在jvm调用中返回相同的值,则应重写该方法以返回自定义值。但是,您应该知道,如果要在基于散列的集合中使用对象,这可能是灾难性的(增加了散列冲突的可能性)

  4. # 5 楼答案

    如果每次都想要相同的值,请使用.ordinal(),或者更好地使用getValue()。您可以覆盖hashCode()的默认值,即根据对象的创建方式为其指定一个数字