Some loose thoughts:
array
is a basic data type that's necessary in any imperative language (maybe in a disguised form). Without array
, how can we implement ArrayList
?:)
However, we could have disguised array
as a "normal" type. For exmple, we could introduce a intrinsic lang.lang.Array<E>
type that does array things, and eliminate the current array
type in Java. (Ignoring primitive arrays, that's another topic). Everything will work out fine.
Yet, we don't have the luxury to "improve" and "clean" the language in a way that breaks backward compatibility.
Before the introduction of generics, array
can be seen as a poor man's generics. We couldn't express ArrayList<String>
, but we could do String[]
. That is why a lot of old APIs return an array, instead of some collection type, because array was more type-safe. array
is even co-variant ... sort of.
After the introduction of generics, the use cases for array
become far fewer. Usually, you should avoid using array in a public API. (Of course, except for var-arg foo(Bar...)
which is array under the hood)
But in the implementation code, we still need array
, it's the basic data structure to build more complex data structures. For that purpose ArrayList
is obviously more bloated in many cases.
Now, the question is, to implement something like ArrayList<E>
, should we use a E[]
, or Object[]
internally? Due to erasure, E[]
is more troublesome - as the saying goes "generics and arrays don't mix well". So forget it, just use Object[]
and do the cast when necessary.