awfun
awfun

Reputation: 2498

Java enum - custom getValues() vs values()

In the project I'm working on I found a strange code:

public enum Service {
    ...
    private static final Service[] values = values();

    public static Service[] getValues() {return values;}
}

Do you have any idea why implementer added his custom method instead of using values() method everywhere? I know, values() method is generated in compile-time, does it affect anything?

Upvotes: 1

Views: 375

Answers (2)

I already did that once with a class because it is the simple way to solve this problem:

  • you have a class A, with methods, and static data (parameters, ...)

  • you want subclasses B1, B2, which use same methods (of B or of A), with its own parameters or parameters of A (depend on B1, B2, ...)

You cant subclass static variables, then you get them by a method you can subclass. And by default, you get A static parameters.

It is not possible with Enum (can not be extended), but perhaps coder wanted to extend. one usefull post: Can enums be subclassed to add new elements?

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

It is because the normal Enum.values() creates a new array every time to make sure the results of the call are always consistent.

This code is removing that and just calling it once. It may be because the coder thought that this could lead to memory leaks/thrashing.

It is a code smell because you could do Service.getValues()[2] = xxx; and corrupt the array for all users.

Upvotes: 4

Related Questions