Thursday, January 12, 2017

<? super T> and <? extends T> in Java

Today, I came across some Java code from a Java library we used, as with many framework/library code bases, it contains lots of Generics, Collections, and Type Wildcards (?). For example: <? super T> and <? extends T> or public static <T extends Comparable<? super T>> void sort(List<T> list) The syntax is complex, and it prompted me to study further the wildcard of Generic types. Thanks to Google and Stack Overflow, the online material is good.


In my own words, which is less precise than in these articles, but maybe easier to understand:

  • If you need to only read through a data structure, declare it with extends, as it can guarantee the object type, and you will be type safe when using the objects.
  • If you need a data structure that allow to put objects into it, then declare it with super, as it allows more type flexibility.

This code example helps show both cases (copied from Generics FAQ):

public class Collections { public static <T> void copy ( List<? super T> dest, List<? extends T> src) { // bounded wildcard parameterized types for (int i=0; i<src.size(); i++) dest.set(i,src.get(i)); } }

As you can see, the src list is declared as extends, since you only need to read from it (get), and the dest list is declared as super, as you need to write to it (set).

Enjoy!

No comments:

Post a Comment