I would like to have somethimng
public enum CategoryTypes
{
Unknown = 0,
One = 1,
Two = 2,
}
in Java? So it could be possible to cast Int to value and vise versa. Is it possible?
Enums in Java are actually classes Singleton instances of the class represented by the enum you created. For the instances to have values, you need to store it in the class, and create a private constructor to set them. Also a getter method would be nice. For example:
public enum MyEnum {
INSTANCE(5),
N2(2);
private int member;
private MyEnum(int member) {
this.member = member;
}
}
int i = Fruit.GRAPE.ordinal() ; // Beware: Horrible misnomer; actually a zero-based index rather than an ordinal.
…and…
Fruit f = Fruit.values()[i] ;
But do not do this! Read on for details.
Enum
Java provides a vastly more useful, flexible, and powerful version of enums.
See:
Enum
classCan be as simple as:
public enum Fruit {
APPLE ,
ORANGE ,
GRAPE
}
To use it:
Fruit f = Fruit.APPLE ;
Usually we have no need for the underlying integer number representing the order in which the elements were defined for the enum. Instead we just use each element of the enum as a normal Java object rather than juggling a mere int number. But if you insist:
Enum::ordinal
to retrieve the a zero-based index number (this method is a terrible misnomer as it is an index rather than a one-based ordinal)int i = Fruit.GRAPE.ordinal() ;
Enum::values
to generate an array which you can access by zero-based indexFruit f = Fruit.values()[i] ;
In doing so, almost certainly you would be failing to take advantage of the full power of the Java enum facility. Using the actual enum objects rather than a mere int
gives you type-safety, ensures valid values, and makes your code more self-documenting.
If your intent is to assign a meaningful code number to each enum instance, do so explicitly by defining a member variable populated by constructor taking that code number, as discussed here and here.
You can add methods and even add constructors taking arguments. Even more to it: EnumSet
and EnumMap
are specialized collections optimized for very little memory and very fast execution.
Set< Fruit > favoriteFruits = EnumSet.of( Fruit.APPLE , Fruit.ORANGE ) ;
Oddly, the EnumSet
does not implement SortedSet
, yet it is documented as returning instances in the order of their enum definition.
Search Stack Overflow for many more discussions and examples.
For a prime example of Enum
in action, see: