How do I write a method which would work on both lists and arrays?

arrays, java, list

Solution

`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),...);
  }
}

Problem

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 `for` loop does? Thanks!

Original source

Related problems