Jump to content

[Mini tutorial] Comparing enums (the right way)


Recommended Posts

Posted (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 by Botre
  • Like 9
  • 5 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...