2

I have an enum that looks like this

public enum MyStates {
                    FIRST,
                    SECOND,
                    THIRD,
                   }

Every time I access them it prints it by the names I have given them. Is there a way to get their indexes? Ex. FIRST would be = 1, and so forth. Thanks

Related:
Enum with int value in Java

5
  • Why do you want indexes, instead of the values that you defined? Commented May 23, 2011 at 15:45
  • 1
    The index of the first element is almost always 0 in Java. (The only exception I can think of is JDBC) Commented May 23, 2011 at 15:49
  • Its not exactly a duplicate. The question here is not about defining a number for each enumeration object but getting its "ordinal". Commented May 23, 2011 at 15:50
  • @morja: If you want it to start from 1, it's not an ordinal. Commented May 23, 2011 at 16:00
  • @SLaks: true, but as I understand it, its only about getting any index, not necessarily starting from 1. Commented May 23, 2011 at 16:02

1 Answer 1

5

Use the ordinal() function.

MyStates.FIRST.ordinal();
Sign up to request clarification or add additional context in comments.

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.