Enums

Enumerators are a commonly used data type to map a value to a predefined set of constants. As the data are entered, an integer iterator enumerates the values beginning with 0 in a plus 1 fashion. You can perform if-then-else style operations on enums using switch statements. Furthermore, it is possible to assign additional values to each enum. This Example will present several basic techniques for using enums.

An enum is useful in various situations. Most commonly, it is used to indicate options. For example, if reading through code and you see a boolean parameter, what does it represent? E.g., linearSearch(array, value, true);. Eventually you figure out that true means forward search as opposed to reverse. An enum in this instance is quite useful: assuming an enum named Search with possible values >FORWARD and REVERSE, we can rewrite the statement as linearSearch(array, value, Search.FORWARD);. This is trivially expanded to include a number of options beyond two.

/**
 * An example {@code enum} class.
 * @author Ray Hylock
 */
public class Enums {
    /** Constructor. */
    public Enums(){}
     
    /**********************************************************************
     *          Simple example using a linear scan array search           *
     **********************************************************************/
    /** Search type enum. */
    public static enum Search { FORWARD, REVERSE };
     
    /**
     * Performs a linear search over the given array in forward or reverse
     * fashion (as determined by {@code search}) in search of the value.
     * @param array     array to search
     * @param value     value to test
     * @param search    search type {@link Search}
     * @return          {@code true} if found, {@code false} otherwise
     */
    public boolean linearSearch(int[] array, int value, Search search){
        int len = array.length;
        switch(search){
            case FORWARD: 
                for(int i=0; i<len; i++) if(array[i] == value) return true;
                break;
            case REVERSE:
                for(int i=len-1; i>=0; i--) if(array[i] == value) return true;
                break;
        }
        return false;
    }
     
    /**********************************************************************
     *   Simple example showing enum comparisons are done as if numeric   *
     **********************************************************************/
    /** Days enum. */
    public static enum Days { SUN, MON, TUE, WED, THU, FRI, SAT };
    public Days day;
     
    /**
     * Sets a day for comparison.
     * @param day day
     */
    public void setDay(Days day){
        this.day = day;
    }
     
    /**
     * Compares the day parameter to the stored day.
     * @param day day to compare
     */
    public void compare(Days day){
        if(this.day == day) System.out.println("Days match.");
        else System.out.println("Days do not match: "
                + this.day + " <> " + day);
    }
     
    /**********************************************************************
     * Complex example, maps message digest hash option to actual values  *
     **********************************************************************/
    /** Java 7+ compliant message digest algorithms. */
    public static enum Algorithms { 
        MD2("MD2"), MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), 
        SHA384("SHA-384"), SHA512("SHA-512");
        String name;
        Algorithms(String algorithm){ name = algorithm; }
    }
     
    /**
     * This simply prints out the parameter and its matching message digest
     * string parameter name.
     * @param algorithm message digest algorithm {@link Algorithms}
     */
    public void messageDigest(Algorithms algorithm){
        System.out.println("Algorithm " + algorithm + " maps to message "
                + "digest string parameter " + algorithm.name);
    }
}

A sample test class is as follows:

import blog.Enums.*;
import static java.lang.System.out;
public class EnumsTest {
    private static Enums e;
    public static void main(String[] args) {
        // setup
        e = new Enums();
         
        // first example - linear serach
        out.println("Linear search example:");
        int values[] = {1,2,3,4,5,6,7,8,9};
        int value[] = {7,0};
        for(int i : value){
            linearSearch(values, i, Search.FORWARD);
            linearSearch(values, i, Search.REVERSE);
        }
         
        // second example - days
        out.println("\nDay example:");
        e.setDay(Days.SUN);
        e.compare(Days.SUN);
        e.compare(Days.MON);
         
        // third example - MD
        out.println("Message digest example:");
        e.messageDigest(Algorithms.SHA512);
    }
     
    /**
     * Performs the linear search and outputs the results.
     * @param values    values array
     * @param value     value to search for
     * @param search    search type
     */
    private static void linearSearch(int[] values, int value, Search search){
        boolean fnd = e.linearSearch(values, value, search);
        if(fnd) out.println("Found "+value+" via "+search+" search");
        else out.println("Value "+value+" not found via "+search+" search");
    }
}

Output from the sample test class:

Linear search example:
Found 7 via FORWARD search
Found 7 via REVERSE search
Value 0 not found via FORWARD search
Value 0 not found via REVERSE search
 
Day example:
Days match.
Days do not match: SUN <> MON
Message digest example:
Algorithm SHA512 maps to message digest string parameter SHA-512