EnumMap Declaration Order Iteration

Key maps by enum constants with EnumMap: an array-backed implementation whose iteration always follows enum declaration order, unlike HashMap.

JavaData Integrity

Code

snippet
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

public class PlantCare {

    enum Season { SPRING, SUMMER, AUTUMN, WINTER }

    public static void main(String[] args) {
        // HashMap 遍历顺序由哈希桶决定,两次运行可能不同
        Map<Season, String> usual = new HashMap<>();
        usual.put(Season.WINTER, "dormant");
        usual.put(Season.SPRING, "sprout");

        // EnumMap 用数组按下标存值:遍历恒等于声明顺序
        Map<Season, String> schedule = new EnumMap<>(Season.class);
        schedule.put(Season.WINTER, "dormant");
        schedule.put(Season.SPRING, "sprout");
        schedule.put(Season.AUTUMN, "harvest");

        schedule.forEach((season, action) ->
                System.out.println(season + " -> " + action));

        // null 键被直接拒绝:枚举类型本身就是键域
        try {
            schedule.put(null, "oops");
        } catch (NullPointerException e) {
            System.out.println("null key rejected");
        }
        System.out.println("spring action: " + schedule.get(Season.SPRING));
        System.out.println("size: " + schedule.size());
    }
}

What the code does

EnumMap Declaration Order Iteration keeps everything in the classes PlantCare and Season and the function main.

Using it

The demo output is labeled (null key rejected, spring action:, size:), so every printed line maps back to its originating operation.

Key statements

Map<Season, String> schedule = new EnumMap<>(Season.class);
Map<Season, String> usual = new HashMap<>();
schedule.put(Season.WINTER, "dormant");

Interactive Tools for This Topic

FAQ

What does EnumMap Declaration Order Iteration print when run?
No setup needed: run the file and look for labeled lines like `null key rejected`, `spring action:`, `size:` in the output.