In Java, there is no Array type collection to make arrays feel more
consistent, such as in inheritance.
Sure there is, it's called List<T>
. The only fundamental difference between a hypothetical Array<T>
and List<T>
is that you can't resize the Array<T>
. If Array<T>
were added it would be just like List<T>
except with less functionality, and what would be the point of that?
Sometimes it makes sense to have a fixed number of elements, some of
which may not be set at a point in time. You might imagine a row of
cupholders; you can put cups in any position or take them out, but you
can't just add another cupholder.
And you can do that with a List<T>
.
List<String> strings = Arrays.asList(new String[45]);
If you don't want to resize your lost, don't resize your list. Any additional functionality available on your data structure you don't need is not hurting you.
However, having extra functionality can be bad when it makes code harder to reason about. Consider:
FooResult result = calculateFoo(myList);
If calculateFoo
takes an interface that cannot resize myList
then it will be easier to understand what the code does. I know the list will be the same size afterwards. But it would be even better if myList was immutable, and then I would know it hasn't change at all.
Having a fixed-size list doesn't seem very useful because either I want a list I can modify (in which case have the option to resize doesn't hurt), or I want a list that cannot be modified. An array type suits neither purpose.