I am trying to write a function that takes some strings and does something with them.
The only thing I'm going to do that the set of strings is loop over them. Right now I end up with an awkward construct along the lines of
public void foo(String[] myStrings){
foo(java.util.Arrays.asList(myStrings));
}
public void foo(Iterable<String> myStrings){
for(String i : myStrings){
bar(i);
}
}
which feels redundant since
for(String i : myStrings){
bar(i);
}
would be perfectly valid code for myStrings of type String[].
Is there a class that I can have foo accept which will allow both collections and arrays?
See Why is an array not assignable to Iterable?
Short answer: no. Array types are synthetic code, as I understand it, and thus do not implement Iterable
or any other types. You need to provide an overloaded method or require clients to call Arrays.asList
at the call site.