Jump to content
Botre

[Mini tutorial] Comparing enums (the right way)

Recommended Posts

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
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Recently Browsing   0 members

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