dagblog.
← Archive

When are enums equal?


Yesterday I skimmed Neater Java, which shows an interesting use of the enum type. I was surprised to see it compare two enum instances using equals. Since an enum value is a constant, I wondered whether I could just test for identity with ==.

I started by looking at Enum#equals(java.lang.Object). It's a final method, and the implementation more or less speaks for itself.

public final boolean equals(Object other) { 
return this==other;
}

I was glad that an identity comparison worked with this implementation of Enum, but it still felt shaky. I didn't want to rely on an implementation detail, so I looked for a definitive answer and found it right in the Java Language Specification, in section 8.9 Enums.

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant. (The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.)

If you use RMI, even indirectly through a remote EJB call, enum types can still cause trouble. RMI-IIOP serialization doesn't handle them properly, though standard Java serialization works. See the bug report Serialization of Enums over IIOP is broke.

Medium version

Related articles

Related CZ Podcast episodes