Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.EnumSet;
import java.util.EnumMap;
enum Directions {
// Abstract method needs to be overriden in each of the enums
// First line of Enum should be always enum declaration. Constructor, variables declaration not allowed.
EAST(0) {
@Override
public void printDirection() {
System.out.println("EAST");
}
},
WEST(180) {
@Override
public void printDirection() {
System.out.println("WEST");
}
},
NORTH(90) {
@Override
public void printDirection() {
System.out.println("NORTH");
}
}, SOUTH(270) {
@Override
public void printDirection() {
System.out.println("SOUTH");
}
};
//We can also define variables like anyother class
int angle;
// This constructor is called for each enum initialization
//Constructor should be private, otherwise it'll allow to initialize objects.
private Directions(int angle) {
this.angle = angle;
}
//Enums allows abstract methods
public abstract void printDirection();
//Also concrete methods can be defined in enum
public int concreteMethod() {
System.out.println("Angle of current method: " + this.angle);
return this.angle;
}
}
public class EnumsExample {
public static void main(String[] args) {
System.out.println(Directions.EAST);
//Calling concrete method
Directions.EAST.concreteMethod();
//Get all the values of enum
Directions[] directions = Directions.values();
for (Directions direction : directions) {
System.out.println(direction);
}
//Get enum object from String
Directions direction = Directions.valueOf("NORTH");
System.out.println(direction);
//Get declaration index of enum
System.out.println(Directions.WEST.ordinal());
//Enums can be compared using both == and .equals() method
System.out.println(Directions.WEST == Directions.valueOf("WEST"));
System.out.println(Directions.WEST.equals(Directions.valueOf("WEST")));
//Use of EnumSet
EnumSet<Directions> set = EnumSet.of(Directions.NORTH, Directions.WEST);
set.add(Directions.EAST);
for (Directions d: set){
System.out.println(d);
}
EnumMap<Directions, Integer> map = new EnumMap<>(Directions.class);
map.put(Directions.NORTH, Directions.NORTH.concreteMethod());
for (Directions d1: map.keySet()){
System.out.println(d1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment