- Как преобразовать значение enum в int?
- 8 ответов
- Enum to Integer and Integer to Enum in Java
- Getting Enum from Integer
- Getting Integer from Enum
- Convert Enum to Int in Java
- Convert Enum to Int in Java
- Related Article — Java Enum
- Convert Enum to / from Integer & String value in java (example)
- Program- convert Enum to/from Integer & String value (java)
- Output – convert Enum to/from Integer & String value (java)
Как преобразовать значение enum в int?
У меня есть функция, которая возвращает тип int. Однако у меня есть только значение перечисления НАЛОГОВ.
Как я могу преобразовать значение перечисления TAX в int?
public enum TAX < NOTAX(0),SALESTAX(10),IMPORTEDTAX(5); private int value; private TAX(int value)< this.value = value; >> TAX var = TAX.NOTAX; // This value will differ public int getTaxValue() < // what do do here? // return (int)var; >
8 ответов
Вам нужно как-то сделать так, чтобы перечисление выставляло value , например
public enum Tax < NONE(0), SALES(10), IMPORT(5); private final int value; private Tax(int value) < this.value = value; >public int getValue() < return value; >> . public int getTaxValue() < Tax tax = Tax.NONE; // Or whatever return tax.getValue(); >
(Я изменил имена, чтобы они были более традиционными и удобочитаемыми, кстати.)
Это предположение , что вы хотите, чтобы значение было присвоено в конструкторе. Если это не то, что вам нужно, вам нужно предоставить нам дополнительную информацию.
Я просто попробовал и понял, что это не удается myEnumValue = MyEnum.valueOf(myInt); аргумент должен иметь тип String — или что-то мне не хватает?
Это решение хуже, чем ничего. Кажется, перечисления в Java просто не следует использовать? Или JDK 1.8 это изменил?
@ebyrob: Учитывая голосование, похоже, что многие люди не согласны с вами, как и я. Если вам нужен фиксированный набор значений, перечисления вполне подойдут.
Прежде чем говорить что-либо о решении, вы должны были посмотреть, кто на него ответил — ДА, Боже, сам Джон Скит !!
//cast enum to int int color = Color.Blue.ordinal();
Это неверно / не рекомендуется Джошуа Блохом в его книге «Эффективная Java» (2-е изд.). См. Пункт 31.
Две причины: во-первых, любая связь между порядковыми значениями и константами будет нарушена, если будут добавлены новые константы, и две, документы API специально не рекомендуют этого.
Так чисто и идеально. Я вижу несколько «не делай этого» и «не рекомендуется». Мне нужно выяснить, почему это считается плохим. Некоторые из раздутых образцов выглядят плохо, ИМО. Так много работы, чтобы выполнить такую простую задачу.
Мне нравится, как в javadoc для ordinal() говорится: «Большинству программистов этот метод не пригодится». На самом деле наличие списка уникальных целых чисел без необходимости присваивать их самому часто является основной причиной, по которой я использую перечисления. Они не «ломаются» при добавлении новых констант, если вы добавляете их в конце. Если вы используете их для связи с внешними программами и не добавляете новое значение во внешнюю программу, то оно все равно не работает. Делал это в течение 20 лет в C и никогда не было никаких проблем. Кроме того, давать «не рекомендуется» в качестве ответа на «почему не рекомендуется» не является причиной 🙂
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.
Convert Enum to Int in Java
This tutorial demonstrates how to convert Enum to Int in Java.
Convert Enum to Int in Java
Java doesn’t provide built-in functionality to convert enum to int or vice versa, but we can create methods to perform these operations. We can convert enum with int values to int using the value() method.
First of all, generate your Enum with int values. In our case:
enum Cars Toyota(10), Mercedes(20), Tesla(30), BMW(40), Audi(50); >
Create a method to get the enum Cars values.
public int getCarAsInt() return cars; >
Create a method to convert the Cars enum member to int. This method will include a for loop and an if conditional statement, which returns the integer value.
public static int convertCarToInt(Cars inputCar) for (Cars cars : Cars.values()) if (cars.getCarAsInt() == inputCar.getCarAsInt()) return cars.getCarAsInt(); > > return -1; >
We can also create a similar method to convert the int to enum Cars .
public static Cars convertIntToCar(int intCars) for (Cars cars : Cars.values()) if (cars.getCarAsInt() == intCars) return cars; > > return null; >
Finally, apply the above methods to each enum member. Let’s try an example and apply each method to each member of the enum Cars , which will convert the enum members to int and int back to the enum member:
package delftstack; enum Cars Toyota(10), Mercedes(20), Tesla(30), BMW(40), Audi(50); private final int cars; Cars(int cars) this.cars = cars; > public int getCarAsInt() return cars; > public static int convertCarToInt(Cars inputCar) for (Cars cars : Cars.values()) if (cars.getCarAsInt() == inputCar.getCarAsInt()) return cars.getCarAsInt(); > > return -1; > public static Cars convertIntToCar(int intCars) for (Cars cars : Cars.values()) if (cars.getCarAsInt() == intCars) return cars; > > return null; > > public class Example public static void main(String[] args) // For enum member Toyota Cars Toyota_Car = Cars.Toyota; int intCars = Toyota_Car.getCarAsInt(); // Get car as integer value System.out.println("Get Toyota car as int value :" + intCars); Toyota_Car = Cars.convertIntToCar(10); // Convert integer value to corresponding car value System.out.println("Convert integer 10 to car enum :" + Toyota_Car); intCars = Cars.convertCarToInt(Cars.Toyota); // Convert Cars value to corresponding integer value System.out.println("Convert Toyota car to integer :" + intCars + "\n"); // For enum member Mercedes Cars Mercedes_Car = Cars.Mercedes; intCars = Mercedes_Car.getCarAsInt(); // Get car as integer value System.out.println("Get Mercedes car as int value :" + intCars); Mercedes_Car = Cars.convertIntToCar(20); // Convert integer value to corresponding car value System.out.println("Convert integer 10 to car enum :" + Mercedes_Car); intCars = Cars.convertCarToInt(Cars.Mercedes); // Convert Cars value to corresponding integer value System.out.println("Convert Mercedes car to integer :" + intCars+ "\n"); // For enum member Tesla Cars Tesla_Car = Cars.Tesla; intCars = Tesla_Car.getCarAsInt(); // Get car as integer value System.out.println("Get Tesla car as int value :" + intCars); Tesla_Car = Cars.convertIntToCar(30); // Convert integer value to corresponding car value System.out.println("Convert integer 10 to car enum :" + Tesla_Car); intCars = Cars.convertCarToInt(Cars.Tesla); // Convert Cars value to corresponding integer value System.out.println("Convert Tesla car to integer :" + intCars+ "\n"); // For enum member BMW Cars BMW_Car = Cars.BMW; intCars = BMW_Car.getCarAsInt(); // Get car as integer value System.out.println("Get BMW car as int value :" + intCars); BMW_Car = Cars.convertIntToCar(40); // Convert integer value to corresponding car value System.out.println("Convert integer 10 to car enum :" + BMW_Car); intCars = Cars.convertCarToInt(Cars.BMW); // Convert Cars value to corresponding integer value System.out.println("Convert BMW car to integer :" + intCars+ "\n"); // For enum member Audi Cars Audi_Car = Cars.Audi; intCars = Audi_Car.getCarAsInt(); // Get car as integer value System.out.println("Get Audi car as int value :" + intCars); Audi_Car = Cars.convertIntToCar(50); // Convert integer value to corresponding car value System.out.println("Convert integer 10 to car enum :" + Audi_Car); intCars = Cars.convertCarToInt(Cars.Audi); // Convert Cars value to corresponding integer value System.out.println("Convert Audi car to integer :" + intCars+ "\n"); > >
The code above will convert each enum Cars member to int and vice versa. See the output:
Get Toyota car as int value :10 Convert integer 10 to car enum :Toyota Convert Toyota car to integer :10 Get Mercedes car as int value :20 Convert integer 10 to car enum :Mercedes Convert Mercedes car to integer :20 Get Tesla car as int value :30 Convert integer 10 to car enum :Tesla Convert Tesla car to integer :30 Get BMW car as int value :40 Convert integer 10 to car enum :BMW Convert BMW car to integer :40 Get Audi car as int value :50 Convert integer 10 to car enum :Audi Convert Audi car to integer :50
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
Related Article — Java Enum
Convert Enum to / from Integer & String value in java (example)
Program- convert Enum to/from Integer & String value (java)
package org.learn; enum Color < RED(10), BLUE(20), GREEN(30), YELLOW(40), BLACK(50); private final int color; Color(int color) < this.color = color; >public int getColorAsInt() < return color; >public String getColorAsString() < return String.valueOf(color); >public static Color convertIntToColor(int iColor) < for (Color color : Color.values()) < if (color.getColorAsInt() == iColor) < return color; >> return null; > public static Color convertStringToColor(String inputColor) < for (Color color : Color.values()) < if (color.getColorAsString().equals(inputColor)) < return color; >> return null; > public static int convertColorToInt(Color inputColor) < for (Color color : Color.values()) < if (color.getColorAsInt() == inputColor.getColorAsInt()) < return color.getColorAsInt(); >> return -1; > public static String convertColorToString(Color inputColor) < for (Color color : Color.values()) < if (color.getColorAsInt() == inputColor.getColorAsInt()) < return color.getColorAsString(); >> return null; > > public class EnumTest < public static void main(String[] args) < Color color = Color.BLACK; int iColor = color.getColorAsInt(); String sColor = color.getColorAsString(); // Get color as integer value System.out.println("1. Get BLACK color as int value :" + iColor); // Get color as String value System.out.println("2. Get BLACK color as string value :" + sColor); color = Color.convertIntToColor(50); // Convert integer value to corresponding color value System.out.println("3. Convert integer 50 to color :" + color); color = Color.convertStringToColor("50"); // Convert String value to corresponding color value System.out.println("4. Convert string 50 to color :" + color); iColor = Color.convertColorToInt(Color.BLACK); // Convert color value to corresponding integer value System.out.println("5. Convert BLACK color to integer :" + iColor); sColor = Color.convertColorToString(Color.BLACK); // Convert color value to corresponding integer value System.out.println("6. Convert BLACK color to String :" + sColor); >>
Output – convert Enum to/from Integer & String value (java)
1. Get BLACK color as int value :50 2. Get BLACK color as string value :50 3. Convert integer 50 to color :BLACK 4. Convert string 50 to color :BLACK 5. Convert BLACK color to integer :50 6. Convert BLACK color to String :50