I am trying to write a generic print method that works for all classes that implements the "Iterable" interface
public class List<T> {
public static <T extends Iterable<T>> void print(T[] list){
for (Object element : list){
System.out.println(element);
}
}
public static void main(String[] args){
ArrayList<Integer> l = new ArrayList();
l.add(1);
l.add(5);
l.add(3);
l.add(2);
print(l);
}
}
but I receive the error "The method print(T[]) in the type List is not applicable for the arguments (ArrayList)"
Your parameter is T[]
. Which is an array of a type that extends Iterable
. You simply want T
. But you also need a type variable for the type parameter in Iterable
. You need
public static <T extends Iterable<E>, E> void print(T list) {
You need this because you don't want an Iterable<ArrayList>
which is what it is in your current implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With