I was going through the enums in Java. It seems that the same things that enums can do can be achieved by collections or an array of Strings or user-defined types.
What is the main purpose of introducing enums in Java 5?
I was going through the enums in Java. It seems that the same things that enums can do can be achieved by collections or an array of Strings or user-defined types.
What is the main purpose of introducing enums in Java 5?
Advantages -
It is used for fields consist of a fixed set of constants.
Example is Thread.State
public enum State {
NEW,
RUNNABLE,
WAITING,
BLOCKED,
...
}
or private enum Alignment { LEFT, RIGHT };
You can restrict input parameter using Enum
like-
String drawCellValue (int maxCellLnghth, String cellVal, Alignment align){}
Here in align parameter could be only Alignment.LEFT
or Alignment.RIGHT
which is restricted.
Example of switch-case with enum
-
String drawCellValue (int maxCellLnghth, String cellVal, Alignment align){
switch (align) {
case LEFT:...
case RIGHT: ...
}
...
}
one of it's uses was as a means to emulate a switch
on Strings type variables as before Java 7 this was not allowed
Have a look for the "type-safe enum pattern" (e.g. in the book "Effective Java" 1st edition, by Joshua Bloch). The Java "enum" construct is a language level support (syntactic sugar) for this design pattern.