Enum in Java
enum Example { A, B, C } --- A, B, C sind drei statische referenzfelder f je ein Objekt vom Typ Example
--- Example.A, Example.B, Example.C
--- es sind 3 konstante Referenzen
--- switch ist moeglich
switch( example )
{ case A:
case B:
case C: }
--- eine Methode f alle drei Objekte
enum Example { A, B, C;
public String toString(){} }
--- eine Methode spezielle für das Objekt A
enum Example { A { public String toString(){} }, B, C }
--- eine Methode spezielle für das Objekt A und
--- eine abstrakte f Enum
enum Example { A { public String toString(){} };
public abstract String toString(){} }
--- eine Wert f Objekte
enum Example { A( "+" ), B( "1" ), C( "x" ); }
Standardmethoden:
Example[] values()
Example valueOf( string )
toString()
Vorteile:
You can use enum constants in a switch statement:
switch (mySquare) {
case O: ...
case Z: ...
case X: ...
}
You couldn't do that if Square was a class.
Bye,
They are:
- Immutable
- Singleton
- Discoverable
- Ordered
- Comparable
- Serializable
- Equatable
- Hashable
- Serializable and deserializable from String
- Extensible
Also:
- Extremely efficient EnumMap and EnumSet
- Very fast in HashMap and HashSet
On the downside:
- A Generic class that's typed to an Enum is a good way to find javac
bugs.
- They consume a lot of resources for what they do.
- Enum.getDeclaringClass()