Home > Blockchain >  How to print enum constants
How to print enum constants

Time:02-26

I have an enum class that I cannot modify. I want to print

JENNIFER MICHAEL WILLIAM

In the Main class that is accessing this Enum class I keep getting this output:

Jenny Mike Will

What code can I write in my Main class to get the output I want?

public enum NickNames

{
    JENNIFER("Jenny"),
    MICHAEL("Mike"),
    WILLIAM("Will");

private final String name;

NickNames(String s) {
    this.name = s;
  }

public String toString() {
      return this.name;
  }

public static String[] getNickNames() {
      String[] output = new String[(values()).length];
      int i = 0; byte b; int j; NickNames[] arrayOfNickNames;
      
      for (j = (arrayOfNickNames = values()).length, b = 0; b < j; ) {
         NickNames h = arrayOfNickNames[b];
        output[i  ] = h.toString(); b  ; 
      }
      
      return output;
  }
}

Here's an example of code that is getting the wrong output.

NickNames[] nn = NickNames.values();
System.out.printf(Arrays.toString(nn));

CodePudding user response:

tl;dr

For a quick simple workaround, see the correct Answer by Mark Rotteveel.

Or, revamp your enum class to define a getDisplayName method rather than overriding toString.

toString is not for user-interface

Your Question is a good example of abusing the override of Object#toString method.

The toString method is designed for use in debugging and logging. Generally not intended for use in the user-interface.

For enums, I would generally advise not overriding toString.

getDisplayName

Instead, add another method to the enum class for the purpose of accessing a name meant for display in the user-interface.

Commonly, such a method is called getDisplayName. For example, Month#getDisplayName and DayOfWeek#getDisplayName.

By the way, an enum should generally be named in the singular.

Tip: Name your parameters descriptively. IDEs commonly display the parameter name in the code editor as a prompt. So NickName( final String displayName ) rather than NickName( final String s ).

Here is some untested example code.

public enum NickName

{
    JENNIFER( "Jenny" ) ,
    MICHAEL( "Mike" ) ,
    WILLIAM( "Will" ) ;

    // Member fields.
    private final String displayName;

    // Constructors.
    NickName( final String displayName ) {
        // Verify argument.
        Objects.requireNonNull( displayName ) ;  
        if( displayName.isBlank() ) { throw new IllegalArgumentException() ; }
        // Remember argument.
        this.name = displayName ;
    }

    // Accessors.
    public String getDisplayName() {
        return this.displayName ;
    }
}

By the way, your getNickNames method is probably not necessary. In modern Java, the calling programmer could just as well write something like this untested code:

String[] nickNames = Arrays.stream( NickName.values() ).map( NickName :: getDisplayName ).toArray() ;

If you believe that to be too much for your particular calling programmers, I suggest changing your implementation of getNickNames to be that one-liner. I found that method’s code in your Question to be difficult to read and comprehend.

And change the name of that method to getDisplayNames for consistency and clarity.

    public static String[] getDisplayNames() {
        return
                Arrays
               .stream( NickName.values() )
               .map( NickName :: getDisplayName )
               .toArray()
    }

Print all enum objects’ name

You said:

I want to print

JENNIFER MICHAEL WILLIAM

Simply call String.join to combine each enum object name.

String output = String.join( " " , NickName.values() ) ;

CodePudding user response:

You can use name() to print the constant name of the enum:

Returns the name of this enum constant, exactly as declared in its enum declaration.

For example:

String concatenatedNickNames = Arrays.stream(NickNames.values())
    .map(NickNames::name)
    .collect(Collectors.joining(" "));
System.out.println(concatenatedNickNames );
  • Related