Java lower bound wildcard

I'm trying to solve this problem and wonder if anyone can explain it

I have three classes of staff, people and angels

Employee extension and human extension angel

When I try to do this Code:

public static void insertElements(List<? super Person> list){
    list.add(new Person("Mike",42));
    list.add(new Employee());
    list.add(new Angel());
}

I received an error

I've been reading the documentation, which means that X or X's superclass (so in my case, angel is the superclass of person) should be allowed? Obviously not!

Who has any good examples that will click on my brain?

Thank you.

Microphone

Solution

Your intuitive logic says: "a list is a person or a super type list of things of person, so I can naturally add an angel. This explanation is wrong

Declaration list List guarantees that the list will be a type that allows any person to be added to the list Since the angel is not alone, the compiler certainly does not allow this Consider calling your method with insertelements (New ArrayList < person >) Can you add angels to such a list? Of course not

The point of understanding the upper and lower limits is that this is fundamentally different from the conventional type specification we are used to List & lt;? Superman > is an undetermined type: it is a pattern of a series of types allowed as parameters When you say person P, then p will always be a person, because an employee is a person On the other hand, the list < person > is not a list , which is a type that matches this pattern rather than its subtype

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>