2

I am trying to define an enum type with Integer values. I am trying to do this because I use this particular value in multiple places in my code and it can only be this. The code below does not work. I guess I am not supposed to use enum like this. Instead should I use a class and put the possible values in an array?

public enum Pitch {
    "60" , "62", "64", "65", "67", "69", "71", "72", "74";

}
2
  • 2
    Doesn't look like you need an enum here. What are you trying to achieve? Suppose this code works, how would you use it? Commented Dec 1, 2014 at 14:36
  • You should note that an enum is a class. Recommended reading: Oracle's tutorial about enum types. Commented Dec 1, 2014 at 14:48

3 Answers 3

3

I'm not sure enum is the best choice here, but you could try something like:

public enum Pitch {
    p60(60), p62(62), ...;

    private final int pitch;

    Pitch(int pitch) {
        this.pitch = pitch;
    }

    public int getValue() {
        return pitch;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

p60(60) is a sign that you don't need an enum.
It is still a valid design if you want to have a finite number of possible values that can be used and have the compiler guard that for you.
I agree with you, but this remains a way of controlling the values that can be entered. That said, of course it would make more sense with more explicit names. Depends of what this pitch is about.
1

You have to specify named LITERALS for enums.

What you can do is

public enum Pitch
{
    SOMENAME(60),
    SOMEOTHERNAME(62),
    // ...
    SOMELASTNAME(74);

    public final int value;

    public Pitch(int val)
    {
        this.value = val;
    }
 }

Then you can access your specific values by name and you can write

Pitch pitch = ...;
int pitchInt = pitch.value;

to work with the values.

Comments

0

If you like to access the values over an index, you should use an array like

String[] pitch = new String[] {
    "60" , "62", "64", "65", "67", "69", "71", "72", "74"
};

An enum is used to dont keep values in mind and give them names instead:

public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

So you access the values over a name instead of an index.

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.