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

StackOverflow https://stackoverflow.com/questions/15241818

  •  18-03-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top