java enum from int

https://‮ww‬w.lautturi.com
java enum from int

In Java, you can use the values() method of an enum type to get an array of all the enum's values in the order they are declared. You can then use the ordinal() method of an enum value to get its position in the values array.

Here's an example of how to get an enum value from an integer in Java:

public enum Size {
    SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

    private String abbreviation;

    private Size(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static Size fromInt(int value) {
        Size[] values = values();
        if (value < 0 || value >= values.length) {
            throw new IndexOutOfBoundsException("Invalid enum value: " + value);
        }
        return values[value];
    }
}

In this example, the Size enum has four constant values: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. The fromInt() method takes an integer as an argument and returns the corresponding enum value.

To get the enum value from the integer, the fromInt() method first calls the values() method to get an array of all the enum's values. It then checks if the integer is within the bounds of the values array, and throws an IndexOutOfBoundsException if it is not. If the integer is within the bounds of the values array, the fromInt() method returns the enum value at the corresponding index.

You can use the fromInt() method to convert an integer to an enum value in Java. This can be useful when you need to convert integers stored in a database or other external source to enum values.

Created Time:2017-11-03 15:57:12  Author:lautturi