0

do java enums are singleton?

for example :

public enum State {

ACTIVE(0),
PENDING(1),
DELETED(2),
}


State s = State.ACTIVE;
State s2 = State.PENDING;
State s3 = State.PENDING;

is java create new instances every time we use State.FOO ??

mohsenJsh
  • 2,048
  • 3
  • 25
  • 49
  • 1
    Your enum has exactly three instances (`ACTIVE`, `PENDING` and `DELETED`) (or would if it was valid code). It does not create new instances every time you reference it. If you had only one element in your enum, instead of three, it would be a singleton. – khelwood Dec 20 '17 at 16:05
  • 1
    "Because there is only one instance of each enum constant, it is permitted to use the ==operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant." ([JLS Sec 8.9.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.1)) – Andy Turner Dec 20 '17 at 16:07

1 Answers1

8

Enums in java are classes with several constant instances of themselves. These are created like static final variables. Accessing an enum constant returns a reference to the enum constant. It does not create a new instance of the enum constant.

cdbbnny
  • 330
  • 2
  • 9