Iterating Enum values

If we want to iterate all the values in the enum, we can use the values() method of enum which returns an array of enum values as enum type.

This method values() is actually inserted by the compiler when it converts our enum into a class with the following method signature. Since the values() method is inserted by the compiler, this method is not present in java.lang.Enum API.

public static enum-type[] values()

Example:
Since values() is a static method, we can call it using enum PizzaSize and it returns an array of PizzaSize values. Then we can iterate the array in many ways. We use enhanced for loop.

PizzaSize[] sizes = PizzaSize.values();

package com.ibytecode.enums;

public class PizzaEnumIterateValues {

	enum PizzaSize {
		SMALL, MEDIUM, LARGE
	};

	public static void main(String[] args) {
		
		PizzaSize[]  sizes = PizzaSize.values();
		for(PizzaSize size : sizes) {
			System.out.println(size);
		}
		
		//ANOTHER WAY TO ITERATE
		for(PizzaSize size : PizzaSize.values()) {
			System.out.print(size + " ");
		}
	}
}

SMALL
MEDIUM
LARGE
SMALL MEDIUM LARGE

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.