I have a method which looks like this:
void foo (List<String> list, ...) {
...
for (String s : list) { // this is the only place where `list` is used
...
}
...
}
the exact same code would work if I replace List<String> list with String[] list, however, to avoid spaghetti code, I keep the single method, and when I need to call it on an array a, I do it like this: foo(Arrays.asList(a)).
I wonder if this is The Right Way.
Specifically,
- What is the overhead of
Arrays.asList()? - Is there a way to write a method which would accept both arrays and lists, just like the
forloop does?
Thanks!
Arrays.asList()has a small overhead. There is no real way to implement one method for bothListandarrays.But you can do the following: