Explain Codes LogoExplain Codes Logo

Best way to create enum of strings?

java
enum
best-practices
design-patterns
Anton ShumikhinbyAnton Shumikhin·Oct 6, 2024
TLDR

The simplest and most effective way to create an enum of strings is to define an enum with a private final String field and a constructor for initializing the value:

public enum Fruit { APPLE("Apple"), BANANA("Banana"), CHERRY("Cherry"); private final String label; Fruit(String label) { this.label = label; // assigning the string value to the enum } public String getLabel() { return label; // tasty getters. Good with ice cream. } @Override public String toString() { return label; // toString: serving fresh fruit names, hot and ready } }

Then, use the getLabel() method or toString() to access the tasty string:

String fruit = Fruit.APPLE.getLabel(); // "Apple" String fruitString = Fruit.APPLE.toString(); // "Apple"

Enums in a nutshell

The untyped string debacle

Relying on bare strings can lead to errors and typos, not to mention it leaves your code hard to read and maintain. This is where Enums come to the rescue, armed with compile-time type safety and fixed constants.

An ego boost for Enums: name() method

The built-in name() method pulls the official name of the enum constant, bragging about its uppercase glory:

String enumName = Fruit.APPLE.name(); // "APPLE"

This serves well when the enum name itself is the string you need.

Enums that do more: Adding methods

Why stop at labels? Flex your enum muscles with methods like toLowerCase() to make your enums code bows:

public enum Fruit { // ... public String toLowerCase() { return label.toLowerCase(); // just chilling, no uppercase drama here } }

These methods can adapt your enums to exactly what your code needs.

Fancy a cup of Enum tea?

When constant strings aren't enough, enums using constructors can handle additional attributes, offering a versatile serving of functionality.

Visualization

Picture an enum as your custom fruit bowl.

Enum FruitBowl { APPLE("Apple"), BANANA("Banana"), CHERRY("Cherry"); private final String fruit; FruitBowl(String fruit) { this.fruit = fruit; } public String getFruit() { return fruit; } }

Here, our fruit bowl has a selection of APPLE, BANANA, and CHERRY.

🍎🍌🍒 FruitBowl 🍎🍌🍒 | Fruit | Fruit Name | | ------------| -----------| | APPLE | "Apple" | | BANANA | "Banana" | | CHERRY | "Cherry" |

Grab any and you know exactly what fruit you're getting - predictable and type-safe.

The art of mastering Enums

Access-anywhere Enums

Designated outside the main class, enums strut their stuff across your code, ensuring clean breaks between classes and making your enums widely available.

Better Control Flow with Enums

Control flow structures like switch cases pair well with enums, offering clear, readable code:

switch(Fruit.APPLE) { // get ready, Apple, you're up! case APPLE: System.out.println("An apple a day keeps the doctor away!") // apple-fan case break; default: break; }

Custom output for Enums

Enums can be trained to output context-specific output.

public enum HTTPStatus { OK(200, "OK"), NOT_FOUND(404, "Not Found"); // HTTPStats: the life of the status party // ... @Override public String toString() { return code + " " + message; // Status check: OK 200 or Not Found 404, no invites lost. } }

The customized string grants elegant readability and usability of enums.

Takeaways from widely accepted solutions

Sometimes, the most upvoted answer gets to the heart of the question: in this case, a solution that uses an overridden toString() method and a private field.

High-level Enum usage

For seasoned coders, interesting discussions can be found on parameterized enums — an in-depth look into enums with generic or parameterized types for heavy lifting.