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,
Arrays.asList()
?for
loop does?Thanks!
Arrays.asList()
has a small overhead. There is no real way to implement one method for both List
and arrays
.
But you can do the following:
void foo (List<String> list, ...) {
...
for (String s : list) { // this is the only place where *list* is used
...
}
...
}
void foo (String[] arr, ...) {
if ( arr != null ) {
foo(Arrays.asList(arr),...);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With