jennifer lawrence
jennifer lawrence

Reputation: 535

are these wildcards redundant?

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?

Upvotes: 1

Views: 64

Answers (2)

Donat
Donat

Reputation: 4813

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.

Upvotes: 1

developer_hatch
developer_hatch

Reputation: 16224

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.

Upvotes: 1

Related Questions