Manually implementing enumerations

An enumeration is type with a fixed (typical small) number of values, e.g., colors (red, green, blue), or marriage status, ...

In [22]:
package lecture;

public class Colors {
    
    public static final Colors red = new Colors("red");
    public static final Colors green = new Colors("green");
    public static final Colors blue = new Colors("blue");
    private static final Colors[] values = { red, green, blue };
    
    private String name;
    
    private Colors(String name) {
        this.name = name;
    }
    
    public static Colors getColor(String name) {
        for(int i = 0; i < values.length; i++)
            if (values[i].name.equals(name))
                return values[i];
        return null;
    }
    
    public String toString() {
        return name;
    }
}
Out[22]:
lecture.Colors
In [24]:
import lecture.Colors;

Colors x = Colors.red;
Colors y = Colors.blue;
Colors z = Colors.red;

System.out.println(x.toString());

return x.equals(z);
red
Out[24]:
true

Enumeration types

In this part we learn about enumeration types in Java. An enumeration is a type whose instances can be one of a fixed number of values declared as part of the type. In Java enumerations are declared like this:

<modifier> enum <enum_name> {
    <value_1>,
    <value_2>,
    ...
    <value_n>
}

Enums are all implicitly subclasses of class java.lang.Enum.

In [2]:
package lecture;

public class Enums {

// we want a type to store a color which can be either red, green, or blue
public enum Colors {
    Red,
    Green,
    Blue
};

// and one to store the texture of an object either rough or smooth 
public enum Texture {
    rough,
    smooth
};
    
}
Out[2]:
lecture.Enums
In [5]:
import lecture.Enums.Colors;
import java.util.Arrays;

Colors myColor = Colors.Red;
Colors myOtherColor = Colors.Blue;
Colors myThirdColor = Colors.Red;

// enums can be compared based on equality
System.out.println("myColor == myThirdColor (both are red): " + (myColor == myThirdColor));

// enums can be toString'ed
System.out.println("myColor.toString(): " + myColor.toString());

// you can access all values of an enum through .values()
System.out.println("all values of Colors: " + Arrays.toString(Colors.values()));

// each value of an enum has an ordinal value associated with it based on its position in the definition of the enum, e.g., Green has ordinal 1 (2nd color)
System.out.println("Ordinal of Green is: " + Colors.Green.ordinal());

// enums support mapping a string to the corresponding enum value
System.out.println("get Green from String - " + Colors.valueOf("Green"));
myColor == myThirdColor (both are red): true
myColor.toString(): Red
all values of Colors: [Red, Green, Blue]
Ordinal of Green is: 1
get Green from String - Green
Out[5]:
null

Fields in Enumeration Types

Enumeration types can have fields that store additional information about a value. Fields are accessed like fields of other objects. To set the values of a field a Enumeration type must define a constructor. For each value of the enumeration, the arguments passed to the constructor are provided in () after the value. Enumeration types can define methods.

In [6]:
package lecture;

public class MoreEnums {
    
    public enum LengthUnits {
        inch(2.5),
        cm(1),
        meter(100);
        
        public double lenInCm;
            
        LengthUnits(double lenInCm) {
            this.lenInCm = lenInCm;
        }
        
        public double convertTo(int quantitiy, LengthUnits target) {
            double targetUnitCm = target.lenInCm;
            double sourceUnitCm = this.lenInCm;
            double ratio = sourceUnitCm / targetUnitCm;
            
            return quantitiy * ratio;
        }
    }
}
Out[6]:
lecture.MoreEnums
In [8]:
import lecture.MoreEnums.LengthUnits;
import static lecture.MoreEnums.LengthUnits.*; // values are implemented internally as static fields of an enumeration type. Thus, we can import them for convenient usage

LengthUnits l = inch;
System.out.println("inch in cm: " + l.lenInCm);

System.out.println("15 inch in cm: " + inch.convertTo(15, cm));
inch in cm: 2.5
15 inch in cm: 37.5
Out[8]:
null

Enums in switch

Expressions that evaluate to an enumeration type can be used as an input to a switch statement.

In [9]:
import lecture.MoreEnums.LengthUnits;
import static lecture.MoreEnums.LengthUnits.*;

LengthUnits l = inch;

switch(l) {
    case inch:
        System.out.println("we are using inch");
        break;
    case cm:
        System.out.println("cm");
        break;
}
we are using inch
Out[9]:
null