A
A
Alexey24112020-08-08 16:08:49
Java
Alexey2411, 2020-08-08 16:08:49

What is the point of masks in Java generics?

For example, in the following example, there will be a compile-time error on all lines where add() is used:

public class Main {
    public static void main(String[] args) {
        List<? extends Fruit> fList = new ArrayList<>();
        List<?> nList = new ArrayList<>();

        fList.add(new Apple()); // Apple extends Fruit
        fList.add(new Fruit()); // Even Fruit itself cannot be added
        fList.add(new Object());
        
        nList.add(new Object());
        nList.add(new Integer(5));
    }
}


And if everything is logical with the nList collection ( We must know the type at compile time ), then with the fList collection - not quite.
Does such a record make sense and is it possible to somehow create such a sheet in which you can add instances of classes derived from the given one ( Without prior upward transformation ) ?

UPD: The issue is resolved, I read about the PECS principle.
Write should be used when we don't need to add anything to the collection, but only read elements from it. If you only need to add elements, you should use the following entry
List<? extends Fruit> fList = new ArrayList<>();
// Здесь коллекция позволяет добавить любой класс ниже Fruit по иерархии ( включительно )
List<? super Fruit> fList = new ArrayList<>();


If we need to do both at the same time, neither super nor extends should be used.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question