Enumerations are not inherently immutable - but you still cannot create a protective copy, since there is only a fixed set of instances - you will need to return a link to one of the existing instances than creating a new instance.
Enumerations usually should be immutable anyway, but to counter claims that they are inherently immutable:
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());
Shortly speaking:
- Make your variables immutable. I canβt remember ever even wanting to create a volatile enumeration.
- You cannot and should not attempt to create protective copies.
source share