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: ...
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With