Reputation: 33
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.
Upvotes: 0
Views: 1203
Reputation: 16910
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
.
Upvotes: 3