Wednesday, March 16, 2016

Enumerations In Java

Creating Enum Types

An enumeration is a data type that allows you to create variables with a list of predefined definitions. The variables created with specific Enum types must be equal to one of the predefined values in the list. They are constants, so the names in the enum are put in upper case. The following example creates an Enum type called "Color" which includes a predefined list of some colors.

public enum Color {
 RED, BLUE, GREEN, YELLOW, BLACK, WHITE, PINK
}
Watch Enum Video

Eclipse Shortcut

If you are using Eclipse you can create a new Enum by right clicking on the package you want to add an Enum to, selecting New, and clicking Enum.

Using The Enum

You can use the Enum like you would use any other variable. Declare the variable with the name of the Enum as the variable type, give the variable an identifier, and assign a value to it. The example below creates two Color variables, checks to see what the color is, and demonstrates what it looks like when you print the variable out.

//Creating Color Variables
Color myFavoriteColor = Color.BLACK;
Color herFavoriteColor = Color.BLUE;
//Checking With Conditional If-Then
if(myFavoriteColor == Color.BLACK){
 System.out.println("Your favorite color is Black!");
}
//Standard toString
System.out.println(myFavoriteColor);
Your favorite color is Black!
BLACK

Looping Through Enumerations

You can loop through all the values of an Enum with a for each loop using the .values() method which returns an array containing all possible values of the specified Enum. The example below loops through all the values in an Enum named Color and prints them to the console.

for(Color aColor:Color.values()){
 System.out.println(aColor);
}
RED
BLUE
GREEN
YELLOW
BLACK
WHITE
PINK

Multiple Enums In A File

It is possible to add multiple enums to a file by placing the Enums within a Class file.

public class Colors{
  public enum DarkColors {RED,BROWN,BLACK}
  public enum LightColors {YELLOW,PINK,WHITE}
  ....
}

You can then access the Enums with their class name followed by the enum name:

Colors myColor = Colors.DarkColors.BLACK;

0 comments:

Post a Comment