0

I would like to use enums to group constant variables in my small program and I would like to set the values so that I can extract the values later and use them as integers.

I am thinking of something like this:

public enum Value {
    THREE = 3,
    SIX = 6, 
    NINE = 9
}

So later I can retrive the value for something like this:

int[] myIntArray = new int[Value.THREE];

I previously used C++ this way but this does not work for me in Java. Is there a way of explicitly setting a Java enumerated value and can someone explain how I would set and then extract the value from my enum?

1
  • You can do this, but there's no point. Just use three constants. Commented Dec 30, 2013 at 8:26

3 Answers 3

5

The syntax of Java is as follows:

public enum NUMBER
{
    THREE(3),
    SIX(6), 
    NINE(9);

    NUMBER(int value){this.value = value;}

    private int value;

    public int getValue(){return value;}
}

Then you can use it like:

int[] myIntArray = new int[NUMBER.THREE.getValue()];
Sign up to request clarification or add additional context in comments.

Comments

2

I would say that's not the logically correct way of using ENUMs. Enums are not of any specific java types (like int float etc). They are types themselves. For example, say to define bank account types,

public enum AccountTYpe
{
    SAVING(1),
    CHECKING(2);

}

Now the advantage of using enum is that for a variable of type AccountTYpe there are only two valid assignments namely the SAVING and CHECKING. Anything else would flag a compile error.

Your requirement seems to be integer constants for which I would suggest to use set of values defined inside an interface as follows

public interface Value {
    Integer THREE = 3;
    Integer SIX = 6;
    Integer NINE = 9;
}

Since the variables defined inside the interface are public static and final you can use them as constants in your code as desired.

int[] myIntArray = new int[Value.THREE]; 

2 Comments

I think that use of Interfaces is a bit of an anti-pattern. It rather defeats the idea of an interface being a functionality contract...
But you can achieve the same thing with either a class or an interface. It doesn't matter which you choose. Many people do prefer classes for this. This is clearly the best of the three answers that are currently here.
0

Use a constructor

public enum Value {
    THREE(3), SIX(6), NINE(9);

    private int value;

    private Value(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.