Víc*_*ugo 7 java enums interface hashcode
为什么每次运行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;
}
}
Run Code Online (Sandbox Code Playgroud)
每次跑步,
public static void main( String[] args ) {
System.out.println( test.A.hashCode() );
}
Run Code Online (Sandbox Code Playgroud)
控制台上会有不同的打印值.为何不一致?
如果您每次都想要相同的值,请使用.ordinal()
或更好,请getValue()
像您拥有的那样使用。您可以覆盖默认值的 hashCode() ,即根据对象的创建方式为其提供一个数字。