Botre Posted August 12, 2016 Posted August 12, 2016 (edited) An enum type member is implicitly static and final, it will always reference the same object. I never ever want to see enum comparison with the equals method again. Use "==". Let's create a simple Animal enum: enum Animal { DOG, CAT, MOUSE; } And a Cage class: class Cage { private final Animal animal; public Cage(final Animal animal) { this.animal = animal; } public final Animal getAnimal() { return animal; } } The following will thrown a null pointer exception: Since the first cage's animal is null, calling the equals() method on it will throw an exception! new Cage(null).getAnimal().equals(new Cage(Animal.DOG).getAnimal()); The following will return false: The first cage's animal is still null, however "==" is not a class method but an operator that allows null on both sides. You are not calling a method on null, therefore no exception will be thrown new Cage(null).getAnimal() == new Cage(Animal.DOG).getAnimal(); The following will return true: new Cage(Animal.DOG).getAnimal().equals(new Cage(Animal.DOG).getAnimal()); The following will also return true: An enum type member is implicitly static and final, it will always reference the same object. You can safely use the "==" operator! AND ALWAYS SHOULD new Cage(Animal.DOG).getAnimal() == new Cage(Animal.DOG).getAnimal(); Edited August 12, 2016 by Botre 9
liverare Posted September 10, 2016 Posted September 10, 2016 (edited) Your justification is convincing, but I'm not comfortable running comparisons against non-primitive/non-wrapped-primitive-object types. Maybe I'll break the habit. Edited September 10, 2016 by liverare 1