You saw in Chapter 3 how to define enumerated types in JDK 5.0 and beyond. Here is a typical example: public enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE }; The type defined by this declaration is actually a class. The class has exactly four instances it is not possible to construct new objects. Therefore, you never need to use equals for values of enumerated types. Simply use == to compare them. You can, if you like, add constructors, methods, and fields to an enumerated type. Of course, the constructors are only invoked when the enumerated constants are constructed. Here is an example. enum Size { SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); private Size(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } private String abbreviation; } All enumerated types are subclasses of the class Enum. They inherit a number of methods from that class. The most useful one is toString, which returns the name of the enumerated constant. For example, Size.SMALL.toString() returns the string "SMALL". The converse of toString is the static valueOf method. For example, the statement Size s = (Size) Enum.valueOf(Size.class, "SMALL"); sets s to Size.SMALL. Each enumerated type has a static values method that returns an array of all values of the enumeration: Size[] values = Size.values(); The short program in Example 5-9 demonstrates how to work with enumerated types. NOTE
Example 5-9. EnumTest.java1. import java.util.*; 2. 3. public class EnumTest 4. { 5. public static void main(String[] args) 6. { 7. Scanner in = new Scanner(System.in); 8. System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) "); 9. String input = in.next().toUpperCase(); 10. Size size = Enum.valueOf(Size.class, input); 11. System.out.println("size=" + size); 12. System.out.println("abbreviation=" + size.getAbbreviation()); 13. if (size == Size.EXTRA_LARGE) 14. System.out.println("Good job--you paid attention to the _."); 15. } 16. } 17. 18. enum Size 19. { 20. SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); 21. 22. private Size(String abbreviation) { this.abbreviation = abbreviation; } 23. public String getAbbreviation() { return abbreviation; } 24. 25. private String abbreviation; 26. } java.lang.Enum 5.0
|