Java - Guidance of using wildcard in generic

less than 1 minute read

Do not use bounded wildcard as a return value

This will force client to use wildcard types

PECS(Produce Extends Consumer Super)

1
2
3
4
5
public void pushAll(Collection<? extends E> src) {
  for (E e : src) {
    push(e)
  }
}
1
2
3
4
5
public void popAll(Collections<? super E> dst) {
  while (!isEmpty()) {
    dst.add(pop())
  }
}

Comparable are always consumer

Comparable<T> can be replaced by Comparable<? super T> and this is true for comparators.
Comparator<T> can be replaced by Comparator<? super T>

The basic guidance of using wildcard in Java generic

https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html