Reputation: 1456
I have the following method that I want to pass arrays of different types:
private < E > void print(E[] arr) {
for(E s: arr) {
System.out.println(s + " ");
}
}
When I pass a List<Double>
array to the print
method, I get the following error:
The method print(E[]) in the type IAnalysisMocker is not applicable for the arguments (List<Double>)
Is there any suggestions of how to solve it?
Upvotes: 3
Views: 526
Reputation: 4699
If you want to pass a list (or any iterable), then change the method signature to this:
private <E> void print(Iterable<E> iterable) {
for(E s: iterable) {
System.out.println(s + " ");
}
}
As the error says The method print(E[]) .. is not applicable for the arguments (List<Double>)
, you can't pass a List<E>
when an array (E[]
) is expected.
Upvotes: 6
Reputation: 65811
Probably the most flexible solution would be to use Iterable<E>
and Arrays.asList
.
private <E> void print(Iterable<E> list) {
for(E s: list) {
System.out.println(s + " ");
}
}
private <E> void print(E[] list) {
print(Arrays.asList(list));
}
You can then print
almost anything and either one or the other method will be invoked.
Upvotes: 0
Reputation: 44150
A list of doubles is not the same as an array of doubles. Change the parameters to List<E> arr
or actually pass it an array.
private <E> void print(List<E> list) {
If you want it to be the "most generic" then Iterable<E>
should be the type of the parameter, since the Java for-each loop works for any implementer of this interface:
private <E> void print(Iterable<E> list) {
Upvotes: 2