Alex Rivera | Logout

Different Enum HashCode generation?

Asked 2012-02-24T18:18:12.203
8

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?

Edit
Report

1 Answer

4

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.

answered 2012-02-24T18:23:56.157

Your Answer