mranders
mranders

Reputation: 1860

How can I convert from a value to an enum?

I have an enum that looks a little bit like this:

public enum Numbers {
  ONE(1), TWO(2), THREE(3);

  public final int num;

  public Numbers(int num) {
    this.num = num;
  }
}

I want to be able to convert from argument to enum, for instance from the int 1 to the enum ONE. Is there any built-in mechanism in Java Enums to do this, or do I have to write my own logic for it?

Upvotes: 2

Views: 741

Answers (3)

Carl
Carl

Reputation: 7544

If you can start your particular enum with ZERO instead, you could do

// ...
private static final Numbers[] list = values();
public static Numbers get(int which) { return list[i]; }
// ...

and ignore assigning indices to your enum.

EDIT: refactor safe option:

//..
private static final Map<Integer, Numbers> getter; static {
 Numbers[] ns = values();
 getter = new HashMap<Integer, Numbers>(ns.length, 1f);
 for (Numbers n : ns) getter.put(n.num, n);
}
public static Numbers get(int which) { return getter.get(which); }
//..

this is also conducive to changing your index to whatever type you like and returns null instead of throwing an exception if you ask for garbage (which can be preferable).

Upvotes: 0

willcodejavaforfood
willcodejavaforfood

Reputation: 44053

If you want conversion from the ordinal you have to do it yourself. There is however automatic conversion from the name of an enum. Btw there is no need to specify the ordinal, that is done automatically and it starts with 0 and there is a ordinal() getter.

Enum.valueOf(Numbers.class, "ONE")

would return Numbers.ONE

Upvotes: 1

Colin Hebert
Colin Hebert

Reputation: 93157

Yes you have to write your own logic as the num variable is a part of your own logic :

public enum Numbers {
    ONE(1), TWO(2), THREE(3);

    public final int num;

    private Numbers(int num) {
        this.num = num;
    }

    public static Numbers getNumber(int i){
        for(Numbers number : Numbers.values()){
            if(i == number.num){
                return number;
            }
        }
        throw new IllegalArgumentException("This number doesn't exist");
    }
}

Upvotes: 8

Related Questions