I have recently taken on a Java course about generics and wildcards. I am not able to grasp the difference between them and, sometimes, even the need to use them.
Two questions, please:
1) An order has a list of products, and we have sheets and clips as products.
public class Product {}
public class Sheet extends Product{}
public class Clip extends Product{}
public class Order {
//isn't this:
private List<Product> products;
//same as this:
private List<? extends Product> products;
}
2.1) When using the first (List<Product>
):
public Order() {//Order constructor, trying to create an order of sheets
this.products = new ArrayList<Sheet>();//compiler asks for cast
}
if I try to compile without casting anyway, error says:
Uncompilable source code - incompatible types: java.util.ArrayList< Sheet > cannot be converted to java.util.List< Product >
then event if I do this:
public Order(){
products = new ArrayList<>();
products.add(new Sheet()); //again asks for a cast
}
try to compile anyways, error says:
Uncompilable source code - Erroneous sym type: java.util.List.add
2.2) When using the second (List<? extends Product>
):
public Order() {//Order constructor, trying to create an order of sheets
this.products = new ArrayList<Sheet>();//compiler asks for cast as well
}
if I try to compile without casting anyway, error says:
incompatible types: java.util.ArrayList< Sheet > cannot be converted to java.util.List< ? extends Product >
then event if I do this:
public Order(){
products = new ArrayList<>();
products.add(new Sheet()); //no suitable method found for add(Sheet),
//method Collection.add(CAP#1) is not applicable
}
try to compile anyways, error says:
Uncompilable source code - Erroneous sym type: java.util.List.add