This is the first day of my participation in the August Text Challenge.More challenges in August


See how many lists in main fail to compile

class Father{ } class Son1 extends Father{ } class Son2 extends Father{ } class GrandSon1 extends Son1{ } class GrandSon2 extends Son1{ } class GrandSon3 extends Son2{ } public class AsListInteface{ public static void main(Sting []args){ List<Father>list1 = Arrays.asList(new Father(), newSon1()); List<Father>list2 = Arrays.asList(new Son1()); List<Father>list3 = Arrays.asList(new Son1, new Son2()); List<Father>list4 = Arrays.asList(new GrandSon1()); List<Father>list5 = Arrays.asList(new GrandSon1, new GrandSon2()); List<Father>list6 = Arrays.asList(new GrandSon2(), new GrandSon3()); List<Father>list7 = Arrays.asList(new GrandSon1(), new GrandSon3()); }}Copy the code

The arrays.asList () method makes ideal assumptions about the type of the generated List, that is, from the perspective of the inheritance tree, the nearest common parent (including its own type) of the types of the arguments must be Father.

Such as

List<Father>list5 = Arrays.asList(new GrandSon1, new GrandSon2());
Copy the code

Since the most recent common parent of GrandSon1 and GrandSon2 classes is Son1, it does not compile well

List<Father>list7 = Arrays.asList(new GrandSon1(), new GrandSon3());
Copy the code

The nearest common parent on the inheritance tree of GrandSon1 and GrandSon3 is Father, so compilation can pass,

So, the question is, why does the Father class fail??

That’s because List is the parent of ArrayList,

But List is not a parent of ArrayList,

Collections are different from arrays. Array Father[] is still the parent of Son[],

So what if you just want to add two classes that don’t have the nearest parent declared?

To do this, set the type information on both sides of the “=”.

ArrayList generated by arrays.asList () cannot be added to the ArrayList. After replacing it with a normal ArrayList, add elements to the ArrayList.

List<Father>list8 = new ArrayList<Father>;
list8.add(new GrandSon1());
list8.add(new GransSon2());
//Collections.addAll(new GrandSon1(), new GrandSon2());
Copy the code

Solution 2: Use wildcards to extend the left type

A List <? extends Father>list9 = Arrays.asList(new GrandSon1, new GrandSon2());
Copy the code

Solution 3: Using generic information, tell the compiler the actual target type on the right:

List<Father>list10= Arrays.<Father>asList(new GrandSon1, new GrandSon2());
Copy the code