How to match a java enum

I've an enum like this:

public enum ChartType
{   
    TABLE(0, false), BAR(1, false), COLUMN(3, false)
    private int type;
    private boolean stacked;
    ChartType(int type, boolean stacked)
    {
        this.type = type;
        this.stacked = stacked;
    }
    public int getType()
    {
        return type;
    }
    public boolean isStacked()
    {
        return this.stacked;
    }
}

I get a charttype (int values like 0,1,3) from the request and want the matching input

Jon Skeet
people
quotationmark

You should create a static method to retrieve a type by number. With just a few charts like this, it's simplest to do that by just running through all the options. For larger enums, you could create a map for quick lookup. The only thing to watch for here is that any static initializers aren't run until after the values have been created.

Simple approach:

public static ChartType fromType(int type) {
    // Or for (ChartType chart : ChartType.getValues())
    for (ChartType chart : EnumSet.allOf(ChartType.class)) {
        if (chart.type == type) {
            return chart;
        }
    }
    return null; // Or throw an exception
}

people

See more on this question at Stackoverflow