- Java enum to number one
- Constructor Summary
- Method Summary
- Methods inherited from class java.lang.Object
- Constructor Detail
- Enum
- Method Detail
- name
- ordinal
- toString
- equals
- hashCode
- clone
- compareTo
- getDeclaringClass
- valueOf
- finalize
- Enum to Integer and Integer to Enum in Java
- Getting Enum from Integer
- Getting Integer from Enum
- Перечисления в Java (java enum)
- Конструкция enum
- Перечисление — это класс
- Элементы перечисления — экземпляры enum -класса, доступные статически
- Название и порядковый номер элемента enum
- Декомпилированный enum-class с наследованием
- Перечисления и параметрический полиморфизм
Java enum to number one
This is the common base class of all Java language enumeration types. More information about enums, including descriptions of the implicitly declared methods synthesized by the compiler, can be found in section 8.9 of The Java™ Language Specification . Note that when using an enumeration type as the type of a set or as the type of the keys in a map, specialized and efficient set and map implementations are available.
Constructor Summary
Method Summary
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
Methods inherited from class java.lang.Object
Constructor Detail
Enum
Sole constructor. Programmers cannot invoke this constructor. It is for use by code emitted by the compiler in response to enum type declarations.
Method Detail
name
Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.
ordinal
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap .
toString
Returns the name of this enum constant, as contained in the declaration. This method may be overridden, though it typically isn’t necessary or desirable. An enum type should override this method when a more «programmer-friendly» string form exists.
equals
hashCode
public final int hashCode()
clone
protected final Object clone() throws CloneNotSupportedException
Throws CloneNotSupportedException. This guarantees that enums are never cloned, which is necessary to preserve their «singleton» status.
compareTo
Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared.
getDeclaringClass
Returns the Class object corresponding to this enum constant’s enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)
valueOf
public static Enum> T valueOf(Class enumType, String name)
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) Note that for a particular enum type T , the implicitly declared public static T valueOf(String) method on that enum may be used instead of this method to map from a name to the corresponding enum constant. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.
finalize
protected final void finalize()
Enum to Integer and Integer to Enum in Java
Need to convert an integer to an enum in Java? The bad news is that it is not as easy as it should be, but the good news is that it is still easy!
public enum PageType < ABOUT(1), CODING(2), DATABASES(3); private int value; private static Mapmap = new HashMap<>(); private PageType(int value) < this.value = value; >static < for (PageType pageType : PageType.values()) < map.put(pageType.value, pageType); >> public static PageType valueOf(int pageType) < return (PageType) map.get(pageType); >public int getValue() < return value; >>
With the above enum, one can get the enum from an integer, but also get the integer based on an enum. The trick here is to use a map internally which handles the mapping of an integer (or whichever type you need) to its corresponding enum. This is done in a static method, which iterates through the values within the enum and adds them to the map. There is also a private constructor where we assign the passed value to a variable. This is done automatically upon using an enum due to the parenthesis after each enum name.
Getting Enum from Integer
To get the enum for a given integer, we simply have to call the valueOf method, like below.
PageType pageType = PageType.valueOf(2); // pageType = PageType.CODING
Getting Integer from Enum
On the other hand, to get the integer value from an enum, one can do as follows, by using the getValue method.
ProductType productType = ProductType.DATABASES; int productTypeId = productType.getValue(); // productTypeId = 3
The getValue method simply returns the internal value of the enum that we store within the value variable.
I hope this helps! Thank you for reading.
Перечисления в Java (java enum)
Программируя мы часто сталкиваемся с необходимостью ограничить множество допустимых значений для некоторого типа данных. Так, например, день недели может иметь 7 разных значений, месяц в году – 12, а время года – 4. Для решения подобных задач во многих языках программирования со статической типизацией предусмотрен специальный тип данных – перечисление ( enum ). В Java перечисление появилось не сразу. Специализированная языковая конструкция enum была введена начиная с версии 1.5. До этого момента программисты использовали другие методы для реализации перечислений.
Конструкция enum
Season season = Season.SPRING; if (season == Season.SPRING) season = Season.SUMMER; System.out.println(season);
В результате выполнения которого на консоль будет выведено SUMMER. Думаю, что пример очевиден и в пояснениях не нуждается.
Перечисление — это класс
Объявляя enum мы неявно создаем класс производный от java.lang.Enum . Условно конструкция enum Season < . >эквивалентна class Season extends java.lang.Enum < . >. И хотя явным образом наследоваться от java.lang.Enum нам не позволяет компилятор, все же в том, что enum наследуется, легко убедиться с помощью reflection :
System.out.println(Season.class.getSuperclass());
Собственно наследование за нас автоматически выполняет компилятор Java. Далее давайте условимся называть класс, созданный компилятором для реализации перечисления — enum -классом, а возможные значения перечисляемого типа — элементами enum -a.
Элементы перечисления — экземпляры enum -класса, доступные статически
Элементы enum Season (WINTER, SPRING и т.д.) — это статически доступные экземпляры enum -класса Season . Их статическая доступность позволяет нам выполнять сравнение с помощью оператора сравнения ссылок == . Пример:
Season season = Season.SUMMER; if (season == Season.AUTUMN) season = Season.WINTER;
Название и порядковый номер элемента enum
Как уже было сказано ранее любой enum -класс наследует java.lang.Enum , который содержит ряд методов полезных для всех перечислений. Пример:
Season season = Season.WINTER; System.out.println("season.name()=" + season.name() + " season.toString()=" + season.toString() + " season.ordinal() lang-java line-numbers"> season.name()=WINTER season.toString()=WINTER season.ordinal()=0
Здесь показано использования методов name() , toString() и ordinal() . Семантика методов — очевидна. Следует обратить внимание, что данные методы enum -класс наследует из класса java.lang.Enum . Получение элемента enum по строковому представлению его имениДовольно часто возникает задача получить элемент enum по его строковому представлению. Для этих целей в каждом enum -классе компилятор автоматически создает специальный статический метод: public static EnumClass valueOf(String name) , который возвращает элемент перечисления EnumClass с названием, равным name . Пример использования:
String name = "WINTER"; Season season = Season.valueOf(name);
В результате выполнения кода переменная season будет равна Season.WINTER . Cледует обратить внимание, что если элемент не будет найден, то будет выброшен IllegalArgumentException, а в случае, если name равен null — NullPointerException. Об этом, кстати, часто забывают. Почему-то многие твердо уверенны, что если функция принимает один аргумент и при некоторых условиях выбрасывает IllegalArgumentException, то при передачи туда null , также будет непременно выброшен IllegalArgumentException. Но это не относится к делу. Продолжим. Получение всех элементов перечисления Иногда необходимо получить список всех элементов enum -класса во время выполнения. Для этих целей в каждом enum -классе компилятор создает метод public static EnumClass[] values() . Пример использования:
System.out.println(Arrays.toString(Season.values()));
[WINTER, SPRING, SUMMER, AUTUMN]
Обратите внимание, что ни метод valueOf() , ни метод values() не определен в классе java.lang.Enum . Вместо этого они автоматически добавляются компилятором на этапе компиляции enum -класса. Добавляем свои методы в enum -класс У Вас есть возможность добавлять собственные методы как в enum -класс, так и в его элементы: То же, но с полиморфизмом:
Последний пример демонстрирует использование наследования в enum . Об этом — далее. Наследование в enum С помощью enum в Java можно реализовать иерархию классов, объекты которой создаются в единственном экземпляре и доступны статически. При этом элементы enum могут содержать собственные конструкторы. Приведем пример:
Здесь объявляется перечисление Type с тремя элементами INT , INTEGER и STRING . Компилятор создаст следующие классы и объекты:
- Type — класс производный от java.lang.Enum
- INT — объект 1-го класса производного от Type
- INTEGER — объект 2-го класса производного от Type
- STRING — объект 3-го класса производного от Type
Три производных класса будут созданы с полиморфным методом Object parse(String) и конструктором Type(. boolean) . При этом объекты классов INT , INTEGER и STRING существуют в единственном экземпляре и доступны статически. В этом можно убедится:
System.out.println(Type.class); System.out.println(Type.INT.getClass() + " " + Type.INT.getClass().getSuperclass()); System.out.println(Type.INTEGER.getClass() + " " + Type.INTEGER.getClass().getSuperclass()); System.out.println(Type.STRING.getClass() + " " + Type.STRING.getClass().getSuperclass());
class Type class Type$1 class Type class Type$2 class Type class Type$3 class Type
Декомпилированный enum-class с наследованием
В подтверждение вышесказанному приведем еще результат декомпиляции перечисления Type из примера выше:
Перечисления и параметрический полиморфизм
У читателя может возникнуть вопрос: "почему вышеуказанное перечисление Type не использует генерики (generics)?". Дело в том, что в Java использование генериков в enum запрещено. Так следующий пример не скомпилируется: