Enum Values Returns A Fresh Array

Tier.values() hands back a new array on every call, so callers mutate their own copy while the shared constant list stays intact; cache it for hot paths.

JavaData Integrity

Code

snippet
public class ValuesSnapshot {

    enum Tier { BRONZE, SILVER, GOLD }

    // 高频路径把数组缓存成常量,避免每次调用都重新分配
    private static final Tier[] ALL_TIERS = Tier.values();

    public static void main(String[] args) {
        Tier[] snapshot = Tier.values();
        Tier[] again = Tier.values();

        // 每次调用都返回新数组:两次调用不是同一个对象
        System.out.println("same array: " + (snapshot == again));

        // 改写自己的副本不会影响枚举常量本身
        snapshot[0] = Tier.GOLD;
        System.out.println("copy mutated: " + snapshot[0]);
        System.out.println("enum intact:  " + Tier.values()[0]);
        System.out.println("cached first: " + ALL_TIERS[0]);
    }
}

How this file behaves — Enum Values Returns A Fresh Array

The snippet is organized around the class ValuesSnapshot and its nested enum Tier, driven by the function main.

What to watch for

  • Import statements, where present, reference standard-library modules only.

Applying it

Entry signature: public static void main(String[] args)

The run prints same array:, copy mutated:, enum intact: — each prefix names the step that produced it.

Statements that matter

Tier[] snapshot = Tier.values();
Tier[] again = Tier.values();
snapshot[0] = Tier.GOLD;

Interactive Tools for This Topic

FAQ

What does Enum Values Returns A Fresh Array print when run?
Execute the whole file; each printed line is prefixed with a label like `same array:`, `copy mutated:`, `enum intact:`.