Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associate enum value to integer

Tags:

java

enums

I have this enum:

public enum Digits {
    ZERO(0);

private final int number;

    private Digits(int number) {
        this.number = number;
    }

    public int getValue(){
        return number;
    }
}

And I would like to make setter in another class which can me offer following feature: - I will give it integer value (in this case, 0) and that setter will set enum ZERO to my local variable of type Digits Is that possible? Many thanks!

like image 503
user5507755 Avatar asked Jan 19 '16 09:01

user5507755


1 Answers

It is possible, but not by invoking the enum's constructor, as it's available only within the enum itself.

What you can do is add a static method in your enum that retrieves the correct instance based on a given value, e.g. ZERO if the given value is 0.

Then you'd invoke that method in your other class when given the int argument.

Self contained example

public class Main {
    static enum Numbers {
        // various instances associated with integers or not
        ZERO(0),ONE(1),FORTY_TWO(42), DEFAULT;
        // int value
        private int value;
        // empty constructor for default value
        Numbers() {}
        // constructor with value
        Numbers(int value) {
            this.value = value;
        }
        // getter for value
        public int getValue() {
            return value;
        }
        // utility method to retrieve instance by int value
        public static Numbers forValue(int value) {
            // iterating values
            for (Numbers n: values()) {
                // matches argument
                if (n.getValue() == value) return n;
            }
            // no match, returning DEFAULT
            return DEFAULT;
        }
    }
    public static void main(String[] args) throws Exception {
        System.out.println(Numbers.forValue(42));
        System.out.println(Numbers.forValue(10));
    }
}

Output

FORTY_TWO
DEFAULT
like image 91
Mena Avatar answered Sep 20 '22 11:09

Mena