1

Why is this enum not valid ?

enum Type{

      MPEG-2=2,PASSED_PIDS_ID=3,DVB=4,ATSC=5,NA=6,UNDETERMINED=7

      }

4 Answers 4

13

You have a couple of syntax errors, one in the first identifier (the - is invalid in a variable name) and also in how you're setting your values. You don't use = in an enum, but you can use a constructor instead. Try this:

enum Type {

    MPEG2(2), PASSED_PIDS_ID(3), DVB(4), ATSC(5), NA(6), UNDETERMINED(7);

    private final int value;

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

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

1 Comment

This is the correct way to go. The ordinal() method on enums is meant to be used by Enum related Data Structures such as EnumSet etc.
2

You can't have a - in an identifier. Use MPEG_2 instead. I also don't think the =[number] syntax is correct in Java.

Comments

2

Remove the =<number>, it is invalid. Also, the minus sign in the first type is not valid syntax.

The Enum has a method called ordinal() which returns the order of the Enum, but it is not recommended to rely on that, should you add any new Enum typed in the future, then the Enums after it in the list will all have an ordinal of one higher.

Should you wish to include some more data, then you can have a constructor, which you could use as example:

public enum Fruit {

    APPLE("Green"),
    BANANA("Yellow");

    private final String colourDescription;

    Fruit(String colourDescription) {
        this.colourDescription = colourDescription;
    }

    public String getColourDescription() {
        return colourDescription;
    }         
}

So for your example, it may be best to have no extra information, or create a constructor as above and pass a number in that way.

5 Comments

How do i make it start from value 2 instead of 1??
@Codenotguru Not possible using ordinal() - will be better to use the constructor in that case.
private constructor? I thought Java enums all wanted to be default access? (ie, Fruit(...){ rather than private Fruit(...){)
@Brian You never want to be able to call new on an enum
@Noel M default access on an enum constructor won't let you call new on it, ever.
1

It's invalid because "-" is not valid character in an identifier. Using MPEG_2 instead of MPEG-2 will fix it.

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.