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;
    }
}
1
  • 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. Jul 30, 2010 at 18:11
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.

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
  • 1
    How do i make it start from value 2 instead of 1??
    – Jony
    Jul 30, 2010 at 17:48
  • @Codenotguru Not possible using ordinal() - will be better to use the constructor in that case.
    – Noel M
    Jul 30, 2010 at 17:49
  • private constructor? I thought Java enums all wanted to be default access? (ie, Fruit(...){ rather than private Fruit(...){)
    – Brian S
    Jul 30, 2010 at 17:53
  • @Brian You never want to be able to call new on an enum
    – Noel M
    Jul 30, 2010 at 17:55
  • @Noel M default access on an enum constructor won't let you call new on it, ever.
    – Brian S
    Jul 30, 2010 at 18:07
1

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.