I have come across a class that has an immutable property:
MyObject[] allObjs
The property is initialized like this:
List<MyObject> objs = createAllMyObjects();
allObjs = objs.toArray(new MyObject[objs.size()]);
When it is exposed through the accessor, it's done as a List:
public List<MyObject> getAllMyObjects() {
return Collections.unmodifiableList(Arrays.asList(allObjs));
}
Why would a programmer do this? Is there a benefit that I don't know about?
Performance is not a concern, as the array of objs will only ever number in a few dozen elements.
It seems that we are going round and round in circles.
The class is a sort of factory, so it's got a private constructor and exposes only static methods (not sure if this could be a reason for the madness).
edit
I guess that my question is really, "Why not just use an internal List<MyObject> allObjs
instead of MyObject[] allObjs
, and return the Collections.unmodifiableList(allObjs)?" as this would accomplish the same thing.