我怎样写这将在两个列表和数组的工作方法? [英] How do I write a method which would work on both lists and arrays?
本文介绍了我怎样写这将在两个列表和数组的工作方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的方法:
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
...
}
...
}
如果我更换了完全相同的code将工作列表与LT;弦乐&GT;列表
与的String []列表
,但是,以避免意大利面条code,我把单一的方法,当我需要调用它阵列上 A
,我这样做是这样的:美孚(Arrays.asList(A))
。
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.
即,
- 什么是开销
Arrays.asList()
? - 有没有写这将接受两个数组和列表,一种方法一种方法,就像
为
循环呢?
- 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?
谢谢!
推荐答案
Arrays.asList()
有一个小的开销。还有就是要实现两个方法之一没有真正的方法列表
和阵列
。
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),...);
}
}
这篇关于我怎样写这将在两个列表和数组的工作方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文