Add Enum Values to ArrayList Example

Java ArrayList Examples


Array Methods with Examples


In this java example, we will demonstrate how to add values of an Enum to a List. This allows us to manipulate the List like any other.

Add Enum Values to ArrayList Example

import java.util.ArrayList;
import java.util.List;

public class EnumIterationExample {
    public static void main(String[] args) {
        System.out.println("Add Enum values to ArrayList:");
        List < DaysOfWeekEnum > days = new ArrayList < > ();
        days.add(DaysOfWeekEnum.FRIDAY);
        days.add(DaysOfWeekEnum.SATURDAY);
        days.add(DaysOfWeekEnum.SUNDAY);
        for (DaysOfWeekEnum day: days) {
            System.out.println(day);
        }
        System.out.println("Remove SATURDAY from the list:");
        days.remove(DaysOfWeekEnum.SATURDAY);
        if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
            System.out.println("Saturday is no longer in the list");
        }
        for (DaysOfWeekEnum day: days) {
            System.out.println(day);
        }
    }
}


enum DaysOfWeekEnum {
    SUNDAY("off"),
        MONDAY("working"),
        TUESDAY("working"),
        WEDNESDAY("working"),
        THURSDAY("working"),
        FRIDAY("working"),
        SATURDAY("off");

    private String typeOfDay;

    DaysOfWeekEnum(String typeOfDay) {
        this.typeOfDay = typeOfDay;
    }

    public String getTypeOfDay() {
        return typeOfDay;
    }

    public void setTypeOfDay(String typeOfDay) {
        this.typeOfDay = typeOfDay;
    }
}
Output:
Add Enum values to ArrayList:
FRIDAY
SATURDAY
SUNDAY
Remove SATURDAY from the list:
Saturday is no longer in the list
FRIDAY
SUNDAY



Comments

  1. Happy to found this blog. Good Post!. It was so good to read and useful to improve my knowledge as updated one, keep blogging. Hibernate Training in Electronic City
    Java Training in Electronic City

    ReplyDelete

Post a comment