'incompatible types: Myclass cannot be converted to CAP#1 where CAP#1 is a fresh type-variable:CAP#1 extends Myclass from capture of ? extends Myclass

In code I created user defined class Myclass and Myclass2 which extends Myclass and then used in ArrayList<? extends Myclass> as a arguments that means now we can pass ArrayList of Myclass and the class which extends Myclass but it is not working it comes up with incompatible types: Myclass cannot be converted to CAP#1 where CAP#1 is a fresh type-variable:CAP#1 extends Myclass from capture of ? extends Myclass

so How we can make such argument that holds object which extends Myclass?

class Myclass{

}

class Myclass2 extends Myclass{

}





public class GenericCheck{

public static void method (ArrayList<? extends Myclass> al){
al.add(new Myclass());

}

public static void main(String args[]){

   ArrayList<Myclass> al = new ArrayList();

   GenericCheck.method(al);

}

}


Solution 1:[1]

There is no problem with the line GenericCheck.method(al);. You can pass an ArrayList<Myclass> to a parameter of type ArrayList<? extends Myclass>. There is no problem there.

The problem is with the line al.add(new Myclass()); inside the method() method. a1 is an ArrayList<? extends Myclass>, which is an ArrayList of unknown type argument. You cannot assume anything about the type argument, except that it is Myclass or a subtype of Myclass. If it is a subclass of Myclass, then adding new Myclass() (a Myclass instance) to it is not allowed. Basically, you cannot guarantee that Myclass is assignable to the unknown type, so you cannot pass it.

More generally, you can think of it through the PECS (Producer extends, Consumer super) idiom. If you use an extends wildcard, the ArrayList can only be used as a "producer" inside the method() method -- you can only get things out of it, and you can never add anything to it (except null). If the parameter had a super wildcard instead (e.g. public static void method (ArrayList<? super Myclass> al)), you would be able to add Myclass to it, though you would only be able to get things out as Object. It is rarely useful to use super wildcards on ArrayList. You probably want no wildcard instead, i.e. public static void method (ArrayList<Myclass> al).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 newacct