Java 5 enums can be compared with ==

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 is © Adrian Smith.
It was originally published on 6 Sep 2007
More on: Java | Language Design | Coding