Collection Interface vs arrays

The easy way to think of it is: Collections beat object arrays in baaasically every single way. Consider:

  • A collection can be mutable or immutable. A nonempty array must always be mutable.
  • A collection can be thread-safe; even concurrent. An array is never safe to publish to multiple threads.
  • A collection can allow or disallow null elements. An array must always permit null elements.
  • A collection is type-safe; an array is not. Because arrays “fake” covariance, ArrayStoreException can result at runtime.
  • A collection can hold a non-reifiable type (e.g. List<Class<? extends E>> or List<Optional<T>>). An array will generate a warning for this.
  • A collection has a full-fledged API; an array has only set-at-index, get-at-index, length and clone.
  • A collection can have views (unmodifiable, subList…). No such luck for an array.
  • A list or set’s equals, hashCode and toString methods do what users expect; on an array they are a common source of bugs.
  • Type-use annotations like @Nullable are extremely confusing with arrays — quick, what does String @Nullable [] mean? (Are you positive?)
  • Because of all the reasons above, third-party utility libraries should not bother adding much additional support for arrays, focusing only on collections, so you also have a network effect. Object arrays will never be first-class citizens in Java APIs.

A couple of the reasons above are covered — but in much greater detail — in Effective Java, Third Edition, Item 28, from page 126.

So, why would you ever use object arrays?

  • You’re very tightly optimizing something
  • You have to interact with an API that uses them and you can’t fix it
    • so convert to/from a List as close to that API as you can
  • Because varargs (but varargs is overused)
    • so … same as previous
  • I can’t think of any other reasons, they suck bad

Leave a Comment