SoFunction
Updated on 2025-04-14

Java uses toString method to display enumeration field information

In Java programming, enum is a special data type that allows programmers to define a fixed set of constants. Enum types are very useful in Java, especially when you need to represent a fixed set of options (such as week, month, direction, etc.). Although enum types may seem simple when defined, in real applications we may want to get the details of enum instances, not just their names. At this time,toStringMethods are particularly important.

toStringThe method isObjectA method in the class, the enum type also inherits the method. By default,toStringMethod returns the name of the enumeration constant. However, we can rewritetoStringMethods to return more useful information, such as enumerating field values ​​for instances.

This article will explain in detail how to rewrite enums in JavatoStringMethod to display the field information of the enumerated instance and provide a complete code example.

1. Enumeration type basics

First, let's review the basics of enum types.

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

In the example above, we define a name calledDayenumeration type, which contains seven days of the week.

If we use();Come to print, the output will beMONDAY,becausetoStringThe method returns the name of the enumeration constant by default.

2. Enumeration type with fields

Sometimes, we might want the enum type to contain more information than just constant names. At this time, we can define fields and constructors in the enum.

public enum DayWithInfo {
    MONDAY("Start of work week"),
    TUESDAY("Second day of work week"),
    WEDNESDAY("Midweek"),
    THURSDAY("Almost end of work week"),
    FRIDAY("End of work week"),
    SATURDAY("Weekend begins"),
    SUNDAY("Rest day");
 
    private final String description;
 
    DayWithInfo(String description) {
         = description;
    }
 
    // Getter for description
    public String getDescription() {
        return description;
    }
}

In this example, we define a name calledDayWithInfoThe enumeration type of each enumeration constant has an associated one withdescriptionField. Through the constructor, we set the corresponding description information for each enum constant.

3. Rewrite the toString method

Now, we want to passtoStringMethod to display the description information of each enumeration constant. To do this, we need to rewritetoStringmethod.

public enum DayWithInfo {
    MONDAY("Start of work week"),
    TUESDAY("Second day of work week"),
    WEDNESDAY("Midweek"),
    THURSDAY("Almost end of work week"),
    FRIDAY("End of work week"),
    SATURDAY("Weekend begins"),
    SUNDAY("Rest day");
 
    private final String description;
 
    DayWithInfo(String description) {
         = description;
    }
 
    public String getDescription() {
        return description;
    }
 
    @Override
    public String toString() {
        return () + ": " + ();
    }
}

In this modified example, we rewrittentoStringMethod, causing it to return the name and description information of the enumeration constant.()Method returns the name of the enumeration constant (e.g.MONDAY),and()Method returns the description information we defined.

IV. Use examples

Now we can useTo print the enum instances and see their details.

public class EnumToStringExample {
    public static void main(String[] args) {
        for (DayWithInfo day : ()) {
            (day);
        }
    }
}

Run the above code and the output will be:

MONDAY: Start of work week
TUESDAY: Second day of work week
WEDNESDAY: Midweek
THURSDAY: Almost end of work week
FRIDAY: End of work week
SATURDAY: Weekend begins
SUNDAY: Rest day

5. Complete code example

For completeness, a complete code example is provided here again, including enumeration definitions and usage examples.

// Enum definition
public enum DayWithInfo {
    MONDAY("Start of work week"),
    TUESDAY("Second day of work week"),
    WEDNESDAY("Midweek"),
    THURSDAY("Almost end of work week"),
    FRIDAY("End of work week"),
    SATURDAY("Weekend begins"),
    SUNDAY("Rest day");
 
    private final String description;
 
    DayWithInfo(String description) {
         = description;
    }
 
    public String getDescription() {
        return description;
    }
 
    @Override
    public String toString() {
        return () + ": " + ();
    }
}
 
// Main class to demonstrate the usage
public class EnumToStringExample {
    public static void main(String[] args) {
        for (DayWithInfo day : ()) {
            (day);
        }
    }
}

6. Practical application and reference value

Rewrite the enumtoStringThe method has wide value in practical applications. The following are some application scenarios:

  • Logging: When recording logs, enumeration constant descriptions containing more information can make the logs clearer and easier to understand.
  • user interface: When displaying enumeration constants on the user interface, using description information instead of simple constant names can improve the user experience.
  • debug: During the debugging process, detailed enumeration information can help developers locate problems faster.
  • Document generation: When generating API documents, including description information of enumeration constants can make the document more complete and useful.

By rewritetoStringMethods, we can easily implement these functions in a Java program without additional code or configuration.

7. Summary

In Java, enum types are a very useful data structure that allows us to define a fixed set of constants. By adding fields and override to enum typestoStringMethod, we can make the enum instance contain more information and display this information when needed. This not only improves the readability and maintainability of the code, but also enhances the functionality and user experience of the program.

This is the end of this article about Java using the toString method to display enumeration field information. For more related Java toString content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!