4

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
user1720500
  • 119
  • 1
  • 2
  • 9
  • 1
    Take a look [here](http://stackoverflow.com/questions/1419835/understanding-enums-in-java/1419849#1419849) for a good answer. – Jonathan Dec 12 '12 at 12:16

3 Answers3

11

Advantages -

  • Set of Constant declaration
  • Restrict input parameter in method
  • Can be usable in switch-case

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: ...
    }
    ...
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • +1 In Java, those "constants" are references to objects which can have immutable data or mutable state, and can be members of sub-classes. – Peter Lawrey Dec 12 '12 at 12:20
0

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

robertboloc
  • 169
  • 4
  • 13
0

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.

Puce
  • 37,247
  • 13
  • 80
  • 152