数组集合:优化code [英] Array to Collection: Optimized code
问题描述
是否有实现这一目标的一个更好的办法?
Is there a better way of achieving this?
public static List<String> toList(String[] array) {
List<String> list = new ArrayList(array.length);
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
注: Arrays.asList(a)返回一个受指定数组支持的固定大小的列表。 (更改返回列表写到数组。)。我不希望这样的行为。我说我的功能上面绕过假设(还是我错了?)
NOTE: Arrays.asList(a) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.). I don't want that behavior. I assume that MY function above bypasses that (or am i wrong?)
所以,在这里我们有另一种方法:
So, here we have the alternative method:
public static List<String> toList(String[] array) {
List<String> list = new ArrayList(array.length);
list.addAll(Arrays.asList(array));
return list;
}
只是看着它,我不相信它比第一种方法更快
推荐答案
你的意思是通过更好的方式:
What do you mean by better way:
更可读的:
List<String> list = new ArrayList<String>(Arrays.asList(array));
更少的内存消耗,也许更快(但绝对不是线程安全):
less memory consumption, and maybe faster (but definitely not thread safe):
public static List<String> toList(String[] array) {
if (array==null) {
return new ArrayList(0);
} else {
int size = array.length();
List<String> list = new ArrayList(size);
for(int i = 0; i < size; i++) {
list.add(array[i]);
}
return list;
}
}
BTW:这里是你的第一个例子中的错误:
Btw: here is a bug in your first example:
array.length
将引发空指针异常,如果数组为null,所以检查如果(阵!= NULL)
必须首先完成。
array.length
will raise a null pointer exception if array is null, so the check if (array!=null)
must be done first.
这篇关于数组集合:优化code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!