Skip to content

Java Generics

illyfrancis edited this page Dec 6, 2013 · 6 revisions

Covariant & Contravariant & Invariant

Very well explained here

But in a nutshell, in Java

  • generics are invariant, e.g. List<String> and List<Object> are inconvertible
  • arrays are covariant, e.g. String[] is a subtype of Object[]

The Get and Put Principle

In the context of covariant and contravariant in generics, there a Get and Put principle that can be used to determine the use of covariant or contravariant.

Use an extends wildcard (covariant) when you only get values out of structure, use a super wildcard (contravariant) when you only put values into a structure, and don't use a wildcard when you both get and put.

Example

This principle at work in the signature of the copy method

public static <T> void copy(List<? super T> dest, List<? extends T> src)

Clone this wiki locally