Why there are different hashCode values for each time you run a java main? Look the example code below.
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;
}
}
For each time you run,
public static void main( String[] args ) {
System.out.println( test.A.hashCode() );
}
there will be different printed values on the console. Why that inconsistency?
If you want the same value each time, use .ordinal()
or even better, use getValue()
like you have. You can override hashCode() from the default which is to give it a number which is based on the way the object was created.
"There's no requirement that hash values be consistent between different Java implementations, or even between different execution runs of the same program."
http://en.wikipedia.org/wiki/Java_hashCode%28%29
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#hashCode%28%29
public static void main( String[] args ) {
System.out.println( test.A.hashCode() );
System.out.println( test.A.hashCode() );
}
This code will now produce same hashCode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With