java – What is the difference between `List<someType> `and` List<? extends someType> `?

Question:

The List<someType> (like List<? extends someType> ) will allow me to add elements of the derived classes from someType.
List<? extends someType> (like List<someType> ) will return an element of type someType when the get () method is called.

What is the difference between them?

Answer:

The Double and Integer classes inherit from Number .

List<Double> doubleList = new ArrayList<Double>();
List<Integer> integerList = new ArrayList<Integer>();
List<Number> numberList = new ArrayList<Number>();

public static void doSomething1(List<? extends Number> list) {
    // ...
}

public static void doSomething2(List<Number> list) {
    // ...
}

doSomething1(numberList);  // ok
doSomething1(doubleList);  // ok
doSomething1(integerList); // ok

doSomething2(numberList);  // ok
doSomething2(doubleList);  // ошибка компиляции
doSomething2(integerList); // ошибка компиляции

Another example:

List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.2);

List<Number> numberList = doubleList; // ошибка компиляции
List<Number> numberList = (List<Number>) doubleList; // ошибка компиляции
List<? extends Number> numberList = doubleList; // ok

Number number = numberList.get(0); // 1.2
Scroll to Top