Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Enum hashCode() refers to the Object hashCode() implementaion, instead of ordinal() function? [duplicate]

I always thought that enum hashCode was referring to ordinal in Java, since ordinal seems to be a perfect candidate for hashCode, but it turns out it enum hashCode actually refers to default hashCode object implementation.

I understand, that this does not contradict JLS, but still this came to me as a surprise, and I can't think why it was made this way. Although I guess JVM, could have relied on this somehow to provide unique guarantees, but this does not hold anymore for 64 bit JVM.

I've checked in JDK 1.6, and latest JDK 7, and this is the same way in both.

Does any one know reason why, it was made this way?

It makes a perfect sense to use ordinal as a hashCode, since it satisfies all the credentials needed plus it is even consistent from one JVM start to the other, which is not required, but nice thing to have.

like image 388
mavarazy Avatar asked Mar 06 '13 07:03

mavarazy


2 Answers

Imagine this trivial, completely made up scenario:

interface MediaType {}

enum BookTypes implements MediaType {
    HARDCOVER;
}

enum MagazineTypes implements MediaType {
    MONTHLY;
}

Map<MediaType, MediaItem> itemMap = new HashMap<MediaType, MediaItem>();
itemMap.put(BookTypes.HARDCOVER, new Book());
itemMap.put(MagazineTypes.MONTHLY, new Magazine());

I think it's pretty clear why you wouldn't want to use ordinal as a hash code in this instance.

like image 80
Perception Avatar answered Nov 03 '22 11:11

Perception


hashcode and ordinal are completely different.

The first instance of every enum would have the same ordinal value, the opposite of a hashcode.

ordinal() Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

enum BookTypes implements MediaType {
    HARDCOVER;  //ordinal is 0
}

enum MagazineTypes implements MediaType {
    MONTHLY; //ordinal is 0
}
like image 35
NimChimpsky Avatar answered Nov 03 '22 13:11

NimChimpsky