Why are borders so weird in Java?

I use Java 8. During training for the transfer of Java OCP 8, I find some pieces of code that I don’t understand and want to know why this is so strange to me.

I have the following hierarchy:

class A {}
class B extends A {}
class C extends B {}

first , this code works:

List<?> list1 = new ArrayList<A>() { 
    { 
        add(new A());
    }
};

But the following code does not work, compilation error:

list1.add(new A());

So why can't we add a new entry this way?

second , this code works:

List<? extends A> list2 = new ArrayList<A>() {
    {
        add(new A());
        add(new B());
        add(new C());
    } 
};

But the following code does not work, compilation error:

list2.add(new A());
list2.add(new B());
list2.add(new C());

And last , this code works:

List<? super B> list3 = new ArrayList<A>() {
    {
        add(new A());
        add(new B());
        add(new C());
    }
};

But in the following code, when we add a new A (), a compilation error:

list3.add(new A()); // compilation error
list3.add(new B());
list3.add(new C());

Thank you for your responses!

+4
source share
2 answers

, . , , :

1, list1 , , List<?>, , ArrayList<A>.

List<?> list1 = ...;  // The compiler knows list1 is a list of a certain type
                      // but it not specified what the type is. It could be
                      // a List<String> or List<Integer> or List<Anything>
list1.add(new A());   // What if list1 was e.g. a List<String>?

:

List<?> list1 = new ArrayList<A>() { 
    { 
        add(new A());
    }
};

list1 . , .. =, ? , ArrayList<A> , add(new A()), .

( 2) .

List<? super B> list3 = new ArrayList<A>() {
    {
        add(new A());
        add(new B());
        add(new C());
    }
};

list3.add(new A()); // compilation error

list3 List<? super B>. , B , A. , a List<B>? A List<B>; .

+3

( " " ) , Java , .

, " , ", , .

:

public interface ListFactory {
    List<?> getList();
}

, - List<?>. :

List<?> list1 = myListFactory.getList();

list1.add(new A());

, , , ListFactory, List<A>, , List<String>.

,

List<?> list1 = new SpecialList();
list1.add(new A());

; : list1.add(new A());, list1. , list1 List<?>, , list1.add(new A()); , - .

( , , : , , . 'd , add(new A()) - , List<A> list2 = new SpecialList();.)

, SpecialList.java; :

public class SpecialList extends ArrayList<A> {
    public SpecialList() {
        add(new A());
    }
}

, , , , ( , A java.util.ArrayList ).

, add(new A()); this.add(new A());. SpecialList() this SpecialList, ArrayList<A> - , , add(new A()) ArrayList<A>.

, , - :

List<?> list1 = new ArrayList<A>() {
    {
        add(new A());
    }
}
list1.add(new A());

3 6 - Java, . 3 SpecialList() - , add(), ArrayList<A>. 6, , , , - , .

, .

+1

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


All Articles