package com.mindprod.example;
import java.util.Arrays;
import java.util.Comparator;
import static java.lang.System.*;
/**
* example use of enum with custom constructor. Enum for shrub
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2011-09-01 initial version
* @since 2011-09-01
*/
enum Shrub
{
SAGEBRUSH( "Artemisia" ),
MAPLE( "Acer" ),
POINSETTIA( "Euphorbia pulcherrima" );
/**
* additional instance field of every BreedM enum constant object
*/
final String latinName;
/**
* constructor
*
* @param latinName Latin name for this shrub
*/
Shrub( String latinName )
{
this.latinName = latinName;
}
String getLatinName()
{
return latinName;
}
}
/**
* example how to sort an array of enums.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2011-09-01 initial version
* @since 2011-09-01
*/
public class TestEnumSort
{
public static void main( String[] args )
{
Shrub[] shrubs = { Shrub.POINSETTIA, Shrub.MAPLE, Shrub.SAGEBRUSH };
Arrays.sort( shrubs );
for ( Shrub shrub : shrubs )
{
out.println( shrub + " " + shrub.getLatinName() );
}
Arrays.sort( shrubs, new InLatinOrder() );
for ( Shrub shrub : shrubs )
{
out.println( shrub + " " + shrub.getLatinName() );
}
}
}
/**
* sort Shrub by Latin name.
* <p/>
* Defines an alternate sort order for Shrub.
* This Comparator code was generated by the Applet at
* http://mindprod.com/applet/comparatorcutter.html
*
* @author ...
* @version 1.0 2011-09-01 - initial release
* @since 2011-09-01
*/
class InLatinOrder implements Comparator<Shrub>
{
/**
* sort by Latin name.
* Defines an alternate sort order for Shrub with JDK 1.5+ generics.
* Compare two Shrub Objects.
* Compares latinName case insensitively.
* Informally, returns (a-b), or +ve if a sorts after b.
*
* @param a first Shrub to compare
* @param b second Shrub to compare
*
* @return +ve if a>b, 0 if a==b, -ve if a<b
*/
public final int compare( Shrub a, Shrub b )
{
return a.latinName.compareToIgnoreCase( b.latinName );
}
}