Since System.out.println accepts all Object s, and you really don't use your generics inside the method, I see no reason to use generics at all. This code will do the same thing:
public static void print(Iterable<?> list) { for (Object element : list) { System.out.println(element); } }
What have you done
I also want to add that you confuse T[] little. T[] means "array type T ". But you are trying to pass it an ArrayList that does not match the array (the ArrayList class uses regular arrays inside, but that doesn't matter).
Let's look at our original method declaration:
public static <T extends Iterable<T>> void print(T[] list) { for (Object element : list) { System.out.println(element); } }
This method is declared as a receiving parameter, which is: An array of generic type T, where generic type T is Iterable over the generic type T.
Let's read this last part again: where the generic type T is Iterable over the generic type T.
That is, the generic type must be iterable over itself.
You will need a class like this to use the current print method:
class MyClass implements Iterable<MyClass> { ... }
And then use your print method as follows:
MyClass[] objects = new MyClass[5]; print(objects);
However, using the current print method, it will only call the MyClass.toString method for each of the 5 elements in the array.
Simon forsberg
source share