Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have to override equals/hashcode for enums which are put in a hashmap

I have a enum class as follows.

public enum Item {
   COKE("Coke", 25), PEPSI("Pepsi", 35), SODA("Soda", 45);
   private String name;
   private int price;

private Item(String name, int price) {
    this.name = name;
    this.price = price;
}

public String getName() {
    return name;
}

public long getPrice() {
    return price;
}
}

and a hashmap defined as follows

private Map<Item, Integer> inventory = new HashMap<Item, Integer>();

Do i need to override hashcode and equals in the enum Item class for inventory.put() and inventory.get() to work properly? If not, why?

like image 935
Saad Avatar asked Aug 27 '17 18:08

Saad


1 Answers

No, you don't. Why? Because reasonable implementations of these methods are already provided.

And even if you wanted to, you couldn't, as these methods are final in enums.

But also, don't use HashMap with an enum key type: use EnumMap, which is specialised for enum keys, and doesn't use hashCode or equals (it actually uses ordinal).


Edit: after reading What is the reason behind Enum.hashCode, I note that the implementations of hashCode and equals are actually those from Object. But these are reasonable, because of the non-instantiability of enum values.

If you can't create a new instance of an enum value, there is no problem with using those defaults:

  • An enum value must have the same hash code value as itself (and it doesn't matter what that value is);
  • An enum value must be equal to itself, and not to any other, i.e. equality by identity.
like image 87
Andy Turner Avatar answered Sep 20 '22 05:09

Andy Turner