Java 5 enums can be compared with ==

By Adrian Smith6 Sep 2007100 words1 mins to read

Java Enum instances are singletons. This seems to be not clearly documented by Sun (at least I found it difficult to find). But it's the case.

What this means is that it's possible to compare enumerated types by identity, which is cool for readability. (And it means that the switch statement works.)

You don't have to write this:

if (PurchaseState.complete.equals(anItem.getPurchaseState()) { ...

You can write:

if (anItem.getPurchaseState() == PurchaseState.complete) { ...

This is documented here in the "discussion" section.

This article was written by Adrian Smith on 6 Sep 2007

Follow me: Facebook | Twitter | LinkedIn | Email

More on: Java | Language Design | Coding