Home | FAQ | Contact me

Java 5 Enumerations, part 2

Here are things you want to do with enums, but were afraid to ask how. Each example is a complete class that

  1. handles at least what's needed to fulfill its objective
  2. adds common or interesting functionality making use thereof
  3. demonstrates common error/exception cases

Table of Contents

Specify ordinal value
Associate names/string

Specify ordinal value

Demonstrate ordinality in enumerations.

package com.etretatlogiciels.examples.enums;

public enum Ordinal
{
  Zero  ( 0 ),
  One   ( 1 ),
  Two   ( 2 ),
  Three ( 3 ),
  Four  ( 4 );

  private int ordinal = 0;

  private Ordinal( int ordinalvalue ) { this.ordinal = ordinalvalue; }

  public int    getOrdinal() { return this.ordinal; }
  public String getName()    { return name(); /* ! */ }
  public String toJson()
  {
    StringBuilder sb = new StringBuilder();
    sb.append( "{ " ).append( "\"ordinal\":\"" + getOrdinal() + "\"" );
    sb.append( " }" );
    return sb.toString();
  }

  public static String nameFromOrdinal( int ordinalvalue )
  {
    if( ordinalvalue > Ordinal.MAXIMUM )
      return null;

    return Ordinal.values()[ ordinalvalue ].getName();
  }

  public static String nameFromOrdinalUnprotected( int ordinalvalue )
  {
    return Ordinal.values()[ ordinalvalue ].getName();
  }

  public static String toJsonList()
  {
    boolean       one = false;
    StringBuilder sb  = new StringBuilder();

    for( Ordinal ordinal : Ordinal.values() )
    {
      if( !one )
      {
        one = true;
        sb.append( "[ " );
      }
      else
      {
        sb.append( ", " );
      }

      sb.append( ordinal.toJson() );
    }

    sb.append( " ]" );
    return sb.toString();
  }

  public static final int MAXIMUM;

  static
  {
    int hi = 0;

    for( @SuppressWarnings( "unused" ) Ordinal ordinal : Ordinal.values() )
      hi++;

    MAXIMUM = hi - 1;
  }

  public static void main( String[] args )
  {
    Ordinal o = Ordinal.Two;

    System.out.println( o );
    System.out.println( o.getName() );
    System.out.println( Ordinal.nameFromOrdinal( 3 ) );
    System.out.println( o.toString() );
    System.out.println( o.toJson() );
    System.out.println( Ordinal.toJsonList() );

    System.out.println( Ordinal.nameFromOrdinal( 9 ) );
    System.out.println( Ordinal.nameFromOrdinalUnprotected( 9 ) );
  }
}

Output from running the main() method above:

  Two
  Two
  Three
  Two
  { "ordinal":"2" }
  [ { "ordinal":"0" }, { "ordinal":"1" }, { "ordinal":"2" }, { "ordinal":"3" }, { "ordinal":"4" } ]
  null
  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
	  at com.etretatlogiciels.examples.enums.Ordinal.nameFromOrdinalUnprotected(Ordinal.java:38)
	  at com.etretatlogiciels.examples.enums.Ordinal.main(Ordinal.java:89)

Associate names/strings

Demonstrate the use of strings with an enumeration. The example here associates ISO two-letter codes with language names and even some alternate language names.

package com.etretatlogiciels.examples.enums;

public enum IsoLanguage
{
  zh ( "Chinese"            ),
  en ( "English"            ),
  fr ( "French"             ),
  gd ( "Gaelic", "Scottish" ),
  gv ( "Gaelic", "Manx"     ),
  de ( "German"             ),
  el ( "Greek"              ),
  es ( "Spanish"            ),
  to ( "Tonga", "Tongan"    ),
  cy ( "Welsh"              ),
  zu ( "Zulu"               );
  // add the other 135+ languages...

  private String name  = null;
  private String name2 = null;

  private IsoLanguage( String name )               { this( name, null ); }
  private IsoLanguage( String name, String name2 ) { this.name = name; this.name2 = name2; }

  public String getCode()  { return name(); /* ! */ }
  public String getName()  { return this.name; }
  public String getName2() { return this.name2; }
  public String toJson()
  {
    StringBuilder sb = new StringBuilder();
    sb.append( "{ " )
      .append( "\"code\":\"" + getCode() + "\", " );
    sb.append( "\"name\":\"" + getName() + "\"" );
    if( this.name2 != null )
      sb.append( ", " ).append( "\"name2\":\"" + getName2() + "\"" );
    sb.append( " }" );
    return sb.toString();
  }

  public static String toJsonList()
  {
    boolean       one = false;
    StringBuilder sb  = new StringBuilder();

    for( IsoLanguage language : IsoLanguage.values() )
    {
      if( !one )
      {
        one = true;
        sb.append( "[ " );
      }
      else
      {
        sb.append( ", " );
      }

      sb.append( language.toJson() );
    }

    sb.append( " ]" );
    return sb.toString();
  }

  public static final String ISOLANGUAGES = toJsonList();

  public static void main( String[] args )
  {
    IsoLanguage l = IsoLanguage.en;

    System.out.println( l );
    System.out.println( l.getName() );
    System.out.println( l.getName2() );
    System.out.println( l.toString() );
    System.out.println( l.toJson() );

    System.out.println( "--------------------" );

    l = IsoLanguage.gv;
    System.out.println( l );
    System.out.println( l.getName() );
    System.out.println( l.getName2() );
    System.out.println( l.getName2() + " " + l.getName() );
    System.out.println( l.toString() );
    System.out.println( l.toJson() );

    System.out.println( "--------------------" );

    System.out.println( IsoLanguage.toJsonList() );
  }
}

Output from running the main() method above:

  en
  English
  null
  en
  { "code":"en", "name":"English" }
  --------------------
  gv
  Gaelic
  Manx
  Manx Gaelic
  gv
  { "code":"gv", "name":"Gaelic", "name2":"Manx" }
  --------------------
  [ { "code":"zh", "name":"Chinese" }, { "code":"en", "name":"English" }, { "code":"fr", "name":"French" }, \
      { "code":"gd", "name":"Gaelic", "name2":"Scottish" }, { "code":"gv", "name":"Gaelic", "name2":"Manx" }, \
      { "code":"de", "name":"German" }, { "code":"el", "name":"Greek" }, { "code":"es", "name":"Spanish" }, \
      { "code":"to", "name":"Tonga", "name2":"Tongan" }, { "code":"cy", "name":"Welsh" }, \
      { "code":"zu", "name":"Zulu" } ]