4

I want to have a Java enum whose values are integers.

For example:

public enum TaskStatus {
    TaskCreated(1), 
    TaskDeleted(2)    
}

But I also want custom names for these two constants like
e.g. "Task Created" and "Task Deleted" (with spaces there).
I want to do it as elegantly as possible without writing
too much additional code.

Can I achieve this without an additional map which
maps the enum constants to their custom names?

I am using JDK 6 in this project.

2
  • By the way, the convention in Java for naming constants is to use all uppercase with underscore between words. So TaskStatus with TASK_CREATED & TASK_DELETED. Commented Jan 18, 2020 at 22:16
  • 1
    Similar: Java enum with lower-case names. Commented Dec 23, 2021 at 17:38

2 Answers 2

17

Just add a field for that:

public enum TaskStatus {
    TaskCreated(1, "Task Created"), 
    TaskDeleted(2, "Task Deleted");

    private final int value;
    private final String description;

    private TaskStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    // Getters etc

    // Consider overriding toString to return the description
}

If you don't want to specify the string, and just want to add a space before each capital letter, that's feasible as well - but personally I'd stick with the above approach for simplicity and flexibility. (It separates the description from the identifier.)

Of course if you want i18n, you should probably just use the enum value name as a key into a resource file.

Sign up to request clarification or add additional context in comments.

3 Comments

You may wish to override the toString() method as a suitable place to return that pretty string value.
@Duncan: Thanks, added that as a comment for something to consider.
Thanks. I'll try this, seems to be exactly what I needed.
4

A minimalistic answer. If the ordinal value suffices, you can do without.

public enum TaskStatus {
    None,
    TaskCreated, 
    TaskDeleted;

    @Override
    public String toString() {
        // Replace upper-case with a space in front, remove the first space.
        return super.toString()
            .replaceAll("\\p{U}", " $0")
            .replaceFirst("^ ", "");
    }
}

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.