Suggested Pages

Tuesday, January 31, 2017

Generics List vs Array

The two most important differences between Array and Generics List are:
  • arrays are covariant;
  • arrays are reified.

Arrays are Covariant


Given a subtype B of a supertype A, the array B[] is a subtype of A[].
Given a subtype B of a supertype A, List<B> is not a subtype of List<A>.

As you can see in the following class, there is a Compiler Error because List<B> is not covariant with List<A> and so it's not a correct overriding.

import java.util.LinkedList;

public class A {
 
 public List<A> doThis(){
  return null;
 }
}
class B extends A {
 
 public List<B> doThis(){ // Compiler Error
  return null;
 }
}
As you can see in the following class, this is a correct overriding because B[] is covariant with A[].


import java.util.LinkedList;

public class A {
 
 public A[] doThis(){
  return null;
 }
}
class B extends A {
 
 public B[] doThis(){
  return null;
 }
}

Arrays are Reified


Arrays enforce element types at runtime, infact it can occur an exception at runtime because of constraints on types. Instead Generics work with erasure, so the contraints are enforced at compile time.

No comments :

Post a Comment

Suggested Pages