1

I have two examples of methods that uses wildcard generics.

First example:

public static <T extends Comparable> T findMax(List<T> list)

Second example:

public static <T extends Comparable<? super T>> T findMax(List<? extends T> list)

I want to know if these two examples are redundant. If yes, why?

2 Answers2

1

The two examples are telling you different things, so they are not redundant, they give different information and restricts the type in a different way.

public static <T extends Comparable> T findMax(List<T> list)

In this example, you are telling your T variable can be of any type that implements or extends Comparable (if it is a class or an interface)

public static <T extends Comparable<? super T>> T findMax(List<? extends T> list)

In this example, you are telling that the T type should extends comparable and also telling that the type must be a super class of T (inside comparable) but it can be a sub-type of T in the list.

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
1

Both wildcards make a difference.

The first one says that T or a supertype of T must implement the Comparable interface. The second one says that you can use a List of objects of type T or of subtype of T.

Donat
  • 4,157
  • 3
  • 11
  • 26