Home | FAQ | Contact me

Java 5 Enumerations, part 5: More fun and games

Here's a surprisingly simple yet occasionally useful implementation of an "incrementing" enumeration.

public enum WhichArgument
{
  unknown, first, second, third, fourth;

  public WhichArgument next()
  {
    return values()[ ordinal() + 1 ];
  }
}

And what we might use it for...

import static java.util.Objects.isNull;
import org.slf4j.Logger;

public class Utilities
{
  private static Logger logger = LoggerFactory.getLogger( Utilities.class );

  private static void validateCodedDataArguments( final String ... arguments )
  {
    WhichArgument which = unknown;

    for( String argument : arguments )
    {
      which = which.next();

      if( isNull( argument ) )
      {
        logger.warn( "Null argument passed; culprit: " + which.name() );
        Thread.dumpStack();
      }
    }
  }
}

Testing this feature's behavior:

@Test
public void testIncrementingEnumeration()
{
  WhichArgument which = WhichArgument.unknown;

  for( int x = 0; x < 10; x++ )
  {
    which = which.next();
    System.out.println( "  " + which.name() );
  }
}

...and the output:

  first
  second
  third
  fourth

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

  at com.windofkeltia.enums.TestEnums$WhichArgument.next(TestEnums.java:31)
  at com.windofkeltia.enums.TestEnums.testIncrementingEnumeration(TestEnums.java:42) <26 internal calls>