Upper bounded generic elements of a VS superclass as method parameters?

As far as I know, using the upper restricted general and using the superclass as a method parameter take the same possible arguments. Which is preferable, and what is the difference between them, if any?

Upper Limited General Parameter:

public <T extends Foo> void doSomething(T foo) {}

Superclass as parameter:

public void doSomething(Foo foo) {}
+4
source share
2 answers

This is a parameter of the upper restricted type. Lower bounds are created using superwhat you really can't do for a type parameter. You cannot have a parameter of the lower restricted type .

, , , List<T>. , :

public <T extends Foo> void doSomething(List<T> foos) {}
public void doSomething(List<Foo> foo) {}

:

class Bar extends Foo { }

:

List<Bar> list = new ArrayList<Bar>();
doSomething(list);

, . , List<Foo> - List<Bar>, Foo - Bar. , , T Bar.

+3

, , //. ( ), .

, :

public static <T> void addToList(List<T> list, T element) {
    list.add(element);
}

, , , :

List<Integer> list = new ArrayList<>();
addToList(list, 7);
//addToList(list, 0.7); // doesn't compile
//addToList(list, "a"); // doesn't compile

:

public static <T> T nullCheck(T value, T defValue) {
    return value != null ? value : defValue;
}

T, , , T.

Integer iN = null;
Integer i = nullCheck(iN, 7);
System.out.println(i); // "7"

Double dN = null;
Double d = nullCheck(dN, 0.7);
System.out.println(d); // "0.7"

Number n = nullCheck(i, d); // T = superclass of Integer and Double
System.out.println(n); // "7"

, , . , .

, List<T> List<Foo>, , , List<? extends Foo>, .

+1

Source: https://habr.com/ru/post/1523958/


All Articles