Although arrays can be used in a for-each loop, they do not implement Iterable
. There are simply two possibilities, either overload the method as you've stated, or just provide only the iterable variant and force the client to call Arrays.asList()
.
In case you want to also provide the array overload, you might change its signature from simple array to varargs:
public void foo(String... myStrings){
foo(java.util.Arrays.asList(myStrings));
}
In such case, beware of the incompatibility between primitive arrays and primitive-wrapper arrays:
static void foo(int... ints) {}
foo(new Integer[] {1, 2}); // compile error
and:
static void foo(Integer... integers) {}
foo(new int[] { 1, 2 }); // compile error
And the most obscure part, with generic varargs:
static <T> T[] foo(T... ts) {
return ts;
}
If you pass an array of Integers:
Integer[] integers = { 1, 2 };
System.out.println(Arrays.deepToString(foo(integers)));
> [1, 2]
The value of ts
is an array of Integers with 2 elements: 1
and 2
.
However, if you pass an array of primitive ints, a funny thing happens:
int[] ints = { 1, 2 };
System.out.println(Arrays.deepToString(foo(ints)));
> [[1, 2]]
In this case, the value of ts is an array of int arrays (int[][]
) with only one element, which is the originally passed array. The reason for this is that an int
isn't an Object
(autoboxing doesn't help here), while an array of ints is, so the value of the T
type parameter becomes int[]
.