Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the difference in variance between arrays and generic types. Which statement is correct?

  • A.Both are invariant, so neither assignment is permitted by the compiler.
  • B.Arrays are covariant, so a String[] is an Object[]; generics are not, so a List<String> is no List<Object>.
  • C.Generics are covariant, so a List<String> is a List<Object>; arrays are not.
  • D.Both are covariant, which is why either can be assigned to a supertype container.

Answer: B

Array covariance is checked at runtime, so assigning a String[] to an Object[] compiles and a bad store then throws ArrayStoreException. Generics were made invariant precisely to move that failure to compile time, which is why a wildcard is needed to accept a family of parameterisations.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.