Convertir Enum a Int en Java

Sheeraz Gul 12 octubre 2023
Convertir Enum a Int en Java

Este tutorial demuestra cómo convertir Enum a Int en Java.

Convertir Enum a Int en Java

Java no proporciona una funcionalidad integrada para convertir enum a int o viceversa, pero podemos crear métodos para realizar estas operaciones. Podemos convertir enumeraciones con valores int a int usando el método value().

Veamos el paso a paso del proceso:

  1. En primer lugar, genera tu Enum con valores int. En nuestro caso:

    enum Cars {
      Toyota(10),
      Mercedes(20),
      Tesla(30),
      BMW(40),
      Audi(50);
    }
    
  2. Cree un método para obtener los valores de la enumeración Cars.

    public int getCarAsInt() {
      return cars;
    }
    
  3. Cree un método para convertir el miembro de enumeración Cars en int. Este método incluirá un bucle for y una declaración condicional if, que devuelve el valor entero.

    public static int convertCarToInt(Cars inputCar) {
      for (Cars cars : Cars.values()) {
        if (cars.getCarAsInt() == inputCar.getCarAsInt()) {
          return cars.getCarAsInt();
        }
      }
      return -1;
    }
    
  4. También podemos crear un método similar para convertir el int en la enumeración Cars.

    public static Cars convertIntToCar(int intCars) {
      for (Cars cars : Cars.values()) {
        if (cars.getCarAsInt() == intCars) {
          return cars;
        }
      }
      return null;
    }
    
  5. Finalmente, aplique los métodos anteriores a cada miembro de enumeración. Probemos un ejemplo y apliquemos cada método a cada miembro de la enumeración Cars, que convertirá los miembros de la enumeración a int e int nuevamente al miembro de la enumeración:

    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");
      }
    }
    

    El código anterior convertirá cada miembro de la enumeración Cars a int y viceversa. Ver la salida:

    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 Gul avatar Sheeraz Gul avatar

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.

LinkedIn Facebook

Artículo relacionado - Java Enum