5

My question is "is it possible to have an int identifier in an enum?" I'm developping a java program and I need to have identifiers that contains numbers and letters but eclips doesn't accept it.

for exapmle public enum Tag{ 5F25, 4F, . . . }

Do anyone know if there is any way to solve this problem! Thank you

San
  • 55
  • 1
  • 7
  • Your problem is "an identifier *starting* with an integer", as you can see in @GGrecs answer, having an int somewhere else isn't a problem. – reto Oct 30 '13 at 13:06
  • Yes you're right. Thank you – San Oct 30 '13 at 13:58

3 Answers3

4

Enum instances must obey the same java language naming restrictions as other identifiers - they can't start with a number.

If you absolutely must have hex in the name, prefix them all with a letter/word, for example the enum class itself:

public enum Tag {
   Tag5F25,
   Tag4F,
   ...
}

or maybe with an underscore and all-caps:

public enum Tag {
   TAG_5F25,
   TAG_4F,
   ...
}

etc

Adam Peck
  • 6,692
  • 3
  • 21
  • 27
Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • I support using an underscore as the prefix, so usage looks like `Tag._5F25` with no redundancy. Will probably have to modify the SonarQube regex for [RSPEC-115](https://rules.sonarsource.com/java/RSPEC-115) though. – Noumenon Jun 16 '20 at 23:33
3

You're trying to bend the laws and conventions of programming. I suggest you take a different approach.

Enums can have constructors. They are usually private, because "instances" of the enum are created inside it. You can provide any info you want (e.g. id, name, keyword etc.).

In this example, I've implemented the enum with just one parameter in the constructor, which is the unique ID you're needing.

public enum Tag
{
    TAG_1(1),
    TAG_2(2),
    TAG_3(3);

    private final int id;

    private Tag(final int id)
    {
         this.id = id;
    }

    public int id() // Objective C style. Can be getId()
    {
         return id;
    }

    /**
     * Bonus method: get a Tag for a specific ID.
     *
     * e.g. Tag tagWithId2 = Tag.getTagForId(2);
     */
    public static Tag getTagForId(final int id)
    {
         for (final Tag tag : values())
              if (tag.id == id)
                   return tag;
         return null;
    }
}
GGrec
  • 8,125
  • 6
  • 35
  • 75
  • +1, I have never expected such thing from an `Enum` to be possible, is this also possible in `C++` ? –  Oct 30 '13 at 13:07
  • 2
    See http://stackoverflow.com/a/3069863/133645 for enum naming conventions (capitals) – reto Oct 30 '13 at 13:07
  • @reto Wrote it off the top of my head, but I agree with you. – GGrec Oct 30 '13 at 13:08
0

In a word, No. Java enum's are basically syntactic sugar for the typesafe enum pattern. This means that the enum is a list of java identifiers: Their names have to follow all the rules for identifiers. One of those rules is that identifier names cannot start with a number.

willkil
  • 1,451
  • 1
  • 18
  • 31