Do you need a defensive copy of Java enumeration types?

People should return so - called "defensive copies" of private reference types This is to avoid returning references to private fields

I wonder if private enumeration types are necessary I read somewhere that enumerations are immutable reference types, so the answer should be "no" Is that right?

Solution

Enumeration itself is not immutable - but you can't create a defensive copy anyway, because only a fixed set of instances are available - you must return a reference to an existing instance instead of creating a new instance

In any case, enumerations should usually be immutable, but to offset the claim that they are immutable in themselves:

enum BadEnum {
    INSTANCE;

    private int foo;

    private int getFoo() {
        return foo;
    }

    public int setFoo(int foo) {
        this.foo = foo;
    }
}

class Test {
    public static void main(String[] args) {
        BadEnum.INSTANCE.setFoo(10);
        System.out.println(BadEnum.INSTANCE.getFoo()); // Prints 10
    }
}

In short:

>Make your enumeration immutable I can't remember even wanting to create a mutable enumeration. > You cannot and should not try to make defensive copies

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>