1

I have enum

enum Number{
  FIRST(123),
  SECOND(321);
}

Number nr=Number.FIRST

How can I get an enum value (not a String but int ) from my variable nr without creating a new method?

2
  • So, are you trying to get the index (0) or the number you have next to FIRST in the declaration (123)? Commented Jun 17, 2013 at 20:58
  • 5
    That enum won't compile. You need a constructor that takes an int. And you will need to create a method. Commented Jun 17, 2013 at 20:59

3 Answers 3

8

In Java, enums are objects too. Provide a constructor for your numbers to be passed in, plus a public instance variable; no getter method necessary.

enum Num{
  FIRST(123),
  SECOND(321);
  public final int value;
  private Num(int value) { this.value = value; }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Uhm, your integer is mutable here
Sure, but the OP did state "without creating a new method".
Eh, you can make it immutable without making it private. Fixed it for you.
Also, +1 for the best (typically terrible) solution!
Note, the private modifier for the enum constructor is redundant, it is private by definition
4

You need to write your enum like this (also, do not call it Number please! There is java.lang.Number):

enum MyNumber
{
    FIRST(123),
    SECOND(321);

    private final int number;

    MyNumber(final int number)
    {
        this.number = number;
    }

    public int getNumber()
    {
        return number;
    }
}

If you don't want an accessor, remove the getter and make number public.

Comments

4

TL;DR: You can't.

Long version:

The code snippet you have above will not compile because you are missing the constructor:

private int value;

public Number(int i) {
    this.value = i;
}

After you've done that, then you will need to provide the getter for value:

public int getValue() {
    return this.value;
}

EDIT: If you really, really, don't want to create a new method, you can make the value field public, but you're violating the OO concept of encapsulation (ie, best practice).

3 Comments

What name conflict? Java doesn't care if you name your class the same as another Class, so long as the fully qualified name is different.
OK, but who on earth will import some.other.package.Number instead of java.lang.Number?
Well, if your client class is on the same package (ie, some.other.package), then some.other.package.Number will be used instead of java.lang.Number unless you import java.lang.Number specifically.

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.