Tuesday 13 December 2011

Java enums: A complete example

I started programming with Pascal, so I have deep feelings for enumerated types. To be honest I feel that they are a much more easy going approach to modeling that the long lists of constants we used in the C programming language or in the pre JDK5 versions of Java.

Java enums are so very flexible and the guide on the Oracle website says it all. What I wanted to do in this post is to provide a full working example, as a reference to myself and hopefully any ... lost soul, that demonstrates how to bind data with each enum type value and also how to implement the previous and next methods,

package gr.abakalidis.sample.model;

/**
 * Possible image states and relative sizes regarding the actual bitmaps
 * loaded from a Web server.
 * 
 * @author Thanassis Bakalidis
 * @version 1.0
 */
public enum ImageState {
    NOT_LOADED(0, 0), SMALL(320, 240), MEDIUM(800, 600), LARGE(1024, 768);

    private final int width;
    private final int height;

    ImageState(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    public int getHeight()
    {
        return this.height;
    }

    public int getWidth()
    {
        return this.width;
    }

    /**
     * Get the next value ion the series of enumeration 
     * 
     * @return the next value in the series or null if already at end of values
     */
    public ImageState getNext()
    {
        return this.ordinal() < ImageState.values().length - 1 
            ? ImageState.values()[this.ordinal() + 1] 
            : null;
    }
 
    /**
     * Get the previous value in the series of enumeration
     * 
     * @return the next value in the series on null if called for the first va;ue 
     */
    public ImageState getPrevious()
    {
        return this.ordinal() == 0 
            ? null 
            : ImageState.values()[this.ordinal() - 1];
    }
}