Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does one need defensive copies for Java enum types?

One should return so-called "defensive copies" of private reference types. That's to avoid returning the reference of a private field.

I would like to know if that's necessary for private enum types. I read somewhere that enums are immutable reference types, so the answer should be 'no'. Is that right?

like image 891
deinocheirus Avatar asked Sep 09 '13 14:09

deinocheirus


People also ask

How are enums stored in memory Java?

In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison.

Is enum typesafe?

The enums are type-safe means that an enum has its own namespace, we can't assign any other value other than specified in enum constants. Typesafe enums are introduced in Java 1.5 Version. Additionally, an enum is a reference type, which means that it behaves more like a class or an interface.

Are enums faster than strings?

Enums are used to hold state and are commonly compared, and enum comparisons are incredibly fast. Much, much faster than comparing strings.

Can enum have different types?

I must answer a resounding no because actually you can't. Enums have their own data type and each enum is essentially a new data type.


1 Answers

Enums aren't inherently immutable - but you wouldn't be able to create a defensive copy anyway, as there's only a fixed set of instances available - you'd have to return a reference to one of the existing instances, rather than creating a new instance.

Enums generally should be immutable anyway, but to counteract the claims that they inherently are 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()); // Prints 10
    }
}

So in short:

  • Make your enums immutable. I can't remember ever even wanting to create a mutable enum.
  • You can't and shouldn't try to make defensive copies.
like image 166
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet