Item 25 - Prefer lists to arrays

From Effective Java 2/e by Joshua Bloch

Arrays v/s Generic type

Arrays (covariant) v/s Generic type (invariant)

  • If Sub is a subtype of Super, then the array type Sub[] is a subtype of Super[]
  • For any two distinct types Type1 and Type2, List<Type1> is neither a subtype nor a supertype of List<Type2>

// Fails at runtime! Object[] objectArray = new Long[1]; objectArray[0] = "I don't fit in"; // Throws ArrayStoreException

// Won't compile! List<Object> ol = new ArrayList<Long>(); // Incompatible types ol.add("I don't fit in");

Arrays (reification) v/s Generic type (erasure)

  • Arrays know and enforce their element types at runtime
  • Generic enforce their type constraints only at compile time and discard (or erase) their element type information at runtime

arrays and generics do not mix well

new List<E>[]
new List<String>[]
new E[]
// List-based generic reduction
static <E> E reduce(List<E> list, Function<E> f, E initVal) {
   List<E> snapshot;
   synchronized(list) {
      snapshot = new ArrayList<E>(list);
   E result = initVal;
   for (E e : snapshot)
      result = f.apply(result, e);
   return result;

Posted by The Finest Artist