Java Language Generics Requiring multiple upper bounds ("extends A & B")


Example

You can require a generic type to extend multiple upper bounds.

Example: we want to sort a list of numbers but Number doesn't implement Comparable.

public <T extends Number & Comparable<T>> void sortNumbers( List<T> n ) {
  Collections.sort( n );
}

In this example T must extend Number and implement Comparable<T> which should fit all "normal" built-in number implementations like Integer or BigDecimal but doesn't fit the more exotic ones like Striped64.

Since multiple inheritance is not allowed, you can use at most one class as a bound and it must be the first listed. For example, <T extends Comparable<T> & Number> is not allowed because Comparable is an interface, and not a class.