我有一个看起来像这样的方法:
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循环一样?谢谢!
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)
| 归档时间: |
|
| 查看次数: |
1255 次 |
| 最近记录: |