Skip to content

Java Generics

illyfrancis edited this page Dec 6, 2013 · 6 revisions

Covariant & Contravariant

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.

The Get and Put Principle

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