0

Assignment: Write a generic static method print() that prints the elements of any object that implements the Iterable<E> interface.

public class ThisUtil
{
    public static <T extends Iterable<T>> void print(T[] anArray) {


        ArrayList<String> stringList = new ArrayList<>();
        for(T element: anArray)
        {
            stringList.add(element.toString());
        }
        String result = String.join(",", stringList);
        System.out.println(result);
    }

    public static void main(String[] args) {
        Integer[] list = {1, 2, 5, 9, 3, 7};
        ThisUtil.print(list);
    }
}

I got error:

no instance(s) of type variable(s) T exist so that Integer conforms to Iterable.

Any help is very appreciated. Thank you advance.

francesco
  • 7,189
  • 7
  • 22
  • 49
David
  • 33
  • 4

1 Answers1

3

Here:

public static <T extends Iterable<T>> void print(T[] anArray)

you say that you will pass array of elements which type extends Iterable but you simply want to iterate over this array. In your case you can change your method signature to :

public static <T> void print(T[] anArray)

because arrays can be used in for-each out of the box.

EDIT :

You are probably looking for something like this :

public static <E, I extends Iterable<E>> void print(I iterable) {

    ArrayList<String> stringList = new ArrayList<>();
    for(E element: iterable) {
        stringList.add(element.toString());
    }
    String result = String.join(",", stringList);
    System.out.println(result);
}

but then you cannot use it with arrays since arrays are not Iterable but the can be used in for-each.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
  • Thank you very much, michalk. But the requirement was using > for any type collections. – David Nov 29 '19 at 07:46
  • So you want to pass array of collections for example? I do not really understand your requirement. And also arrays are not collections... – Michał Krzywański Nov 29 '19 at 07:47
  • Assignment: Write a generic static method print() that prints the elements of any object that implements the Iterable interface. – David Nov 29 '19 at 07:53
  • Your first suggestion can be written as `public static void print(Object[] anArray)` and your second suggestion can be written as `public static void print(Iterable> iterable)` – newacct Jan 19 '20 at 07:05