Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic list print method

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)"

like image 481
manis Avatar asked Jan 06 '14 19:01

manis


1 Answers

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.

like image 183
Sotirios Delimanolis Avatar answered Sep 28 '22 00:09

Sotirios Delimanolis