6

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?

azro
  • 53,056
  • 7
  • 34
  • 70
Saad
  • 915
  • 9
  • 19
  • Are you looking for this https://stackoverflow.com/questions/4885095/what-is-the-reason-behind-enum-hashcode ? – Naman Aug 27 '17 at 18:16
  • Or have you ended up with something like this https://stackoverflow.com/questions/40028231/apache-commons-lang3-hashcode-equals-and-tostring-including-enums? – Naman Aug 27 '17 at 18:18
  • 1
    Also check `EnumMap`. – lexicore Aug 27 '17 at 18:49

1 Answers1

13

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.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • But if Item was a class then we must override hashcode and equals in order for them to work in a Map. So What difference changing it to an enum makes? – Saad Aug 27 '17 at 18:15
  • All enums are subclasses of `Enum`. This class provides final implementations of [`equals`](https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#equals-java.lang.Object-) and [`hashCode`](https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#hashCode()) – Andy Turner Aug 27 '17 at 18:20