Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Enum HashCode generation?

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?

like image 646
Víctor Hugo Avatar asked Feb 24 '12 18:02

Víctor Hugo


2 Answers

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.

like image 78
Peter Lawrey Avatar answered Sep 22 '22 05:09

Peter Lawrey


"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.

like image 22
jn1kk Avatar answered Sep 23 '22 05:09

jn1kk