Java Reference
In-Depth Information
public void execute() {
System.out.println("Running...");
}
},
JUMP {
public void execute() {
System.out.println("Jumping...");
}
};
// Force all constants to implement the execute() method.
public abstract void execute();
}
Listing 18-10. Using the CommandList Enum Constants as Command Types
// CommandTest.java
package com.jdojo.enums;
public class CommandTest {
public static void main(String... args) {
// Execute all commands in the command list
for(Command cmd : CommandList.values()) {
cmd.execute();
}
}
}
Running...
Jumping...
Reverse Lookup for Enum Constants
You can get the reference of an enum constant if you know its name or position in the list. This is known as reverse
lookup based on the name or ordinal of an enum constant. You can use the valueOf() method, which is added by
the compiler to an enum type, to perform reverse lookup based on a name. You can use the array returned by the
values() method, which is added by the compiler to an enum type, to perform reverse lookup by ordinal. Note that
the order of the values in the array that is returned by values() method is the same as the order in which the enum
constants are declared. The ordinal of enum constants starts at zero. This implies that the ordinal value of an enum
constant can be used as an index in the array that is returned by the values() method. The following snippet of code
demonstrates how to reverse look up enum constants:
Severity low1 = Severity.valueOf("LOW"); // A reverse lookup using a name
Severity low2 = Severity.values()[0]; // A reverse lookup using an ordinal
System.out.println(low1);
System.out.println(low2);
System.out.println(low1 == low2);
 
Search WWH ::




Custom Search