假设 List 的大小很大(可能是 1,000 个对象),以下哪一种方法不会受到性能影响。
我)
List<String> myList = new ArrayList<String>();
for(int i=0; i <=10; i++){
myList.add(""+i);
}
String[] array = myList.toArray(new String[myList.size()]);
myArrayMethod(array); // this method returns the array - it modifies the content but not size of array.
myListMethod(myList); // this method processes the list.
ii)
List<String> myList = new ArrayList<String>();
for(int i=0; i <=10; i++){
myList.add(""+i);
}
String[] array = new String[myList.size()];
int i = 0;
for(String str : myList){
array[i] = myList.get(i);
i++;
}
myArrayMethod(array); // this method returns the array - it modifies the content but not size of array.
myListMethod(myList); // this method processes the list.
最佳答案
第一个示例稍微高效一些,因为它可以在内部使用 System.arraycopy()。
但是,与您正在做的其他事情相比,例如创建字符串,这没什么区别,我建议你做你认为更清楚的事情
关于java - toArray(new MyObject[size]) 与遍历列表并填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5584898/