Java Enums are cool. I've never looked at them in depth until the other day. I'd used them to do the basic things you expect you can do things like this:
public class EnumTest {
public enum Fruit {
ORANGE, APPLE, PEAR;
}
}
But there's a lot more to them as I discovered. Because enums are objects derived from the
java.lang.Enum you can do a lot more. You can get a the value of the Enums:
System.out.println(Fruit.PEAR.ordinal());
You can define methods and constructors and instance variables like this:
public enum Fruit {
ORANGE("orange"),APPLE("red"),PEAR("green");
String color;
Fruit(String c) {
color = c;
}
public String getColor() { return color; }
}
Just when you thought it couldn't get any better, there's more still. There's some great things that come with being able to do EnumSets and EnumMaps. And EnumMaps are nice and efficient because they are represented internally with arrays.
public static void printList(){
for(Fruit f:EnumSet.allOf(Fruit.class)) {
System.out.println(f);
}
}
Labels: software
1 Comments: Post a Comment
Hubert, I got a good chuckle reading this blog... Sunny got a laugh too... :)
Michael