Are Java enums considered primitive or reference types?
If I have an enum object, is it considered a primitive or a reference?
Solution 1:
It's a reference type. Java primitives are boolean byte short char int long float double
.
You can get the enumeration constant's value by calling ordinal()
, which is used by EnumSet and EnumMap iterator
and "traverses the elements in their natural order (the order in which the enum constants are declared)"
You can even add your own members to the enum class, like this:
public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; } };
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
//Elsewhere:
Operation op = Operation.PLUS;
double two = op.eval(1, 1);
Solution 2:
The way enums work is actually not too different from how they were used before their introduction with Java 5:
public final class Suit {
public static final Suit CLUBS = new Suit();
public static final Suit DIAMONDS = new Suit();
public static final Suit HEARTS = new Suit();
public static final Suit SPADES = new Suit();
/**
* Prevent external instantiation.
*/
private Suit() {
// No implementation
}}
By instantiating the different suits on class loading it is ensured that these will be mutually exclusive and the private constructor ensures that no further instances will be created.
These would be comparable either through == or equals.
The Java 5 enum works pretty much the same way, but with some necessary features to support serialization etc.
I hope this background sheds some further light.