Generics wildcard not working

Having looked at the following code, why is the second dump call not compiled? And how can I fix this without deleting the template?

import java.util.ArrayList;
import java.util.List;

class Column<A, T extends Object> {
}

public class Generics {

  static void main(String[] args) {
    Integer i = 5;

    // this works
    List<Column<Integer, ?>> columns1 = new ArrayList<Column<Integer, ?>>();
    dump(columns1, i);

    // this doesn't
    List<Column<Integer, String>> columns2 = new ArrayList<Column<Integer, String>>();
    dump(columns2, i);
  }

  static <A, T> void dump(Iterable<Column<A, ?>> columns, A value) {
    for (Column<A,?> col: columns) {
      System.out.println(col);
    }
  }

}

JDK compiler gives

Generics.java:18: <A,T>dump(java.lang.Iterable<Column<A,?>>,A) in Generics cannot be applied to (java.util.List<Column<java.lang.Integer,java.lang.String>>,java.lang.Integer)
 dump(columns2, i);

    ^
1 error
+5
source share
1 answer

Since columnsin dump()acts as a producer of objects, you need to declare it with extends(general rule: "producer - extends, consumer - super"):

static <A, T> void dump(Iterable<? extends Column<A, ?>> columns, A value) {
    for (Column<A,?> col: columns) {
        System.out.println(col);
    }
}
+5
source

All Articles