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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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.

Got any Java Language Question?