如何编写可在列表和数组上工作的方法?

sds*_*sds 4 java arrays list

我有一个看起来像这样的方法:

void foo (List<String> list, ...) {
  ...
  for (String s : list) { // this is the only place where `list` is used
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

如果我替换List<String> list,完全相同的代码将工作String[] list,但是,为了避免意大利面条代码,我保持单一方法,当我需要在数组上调用它时a,我这样做:foo(Arrays.asList(a)).

我想知道这是不是正确的方法.

特别,

  • 什么是开销Arrays.asList()
  • 有没有办法编写一个接受数组和列表的方法,就像for循环一样?

谢谢!

Jér*_*nge 6

Arrays.asList()开销很小.没有真正的方法来实现两种方法List和一种方法arrays.

但是你可以做到以下几点:

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),...);
  }
}
Run Code Online (Sandbox Code Playgroud)