考虑以下两个代码片段:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0);
for (int i=1; i<10; i++)
list.add(i);
和
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<10; i++)
list.add(i);
list.add(0,0);
我真的很想知道这两种情况下是否存在任何性能差异?我在想的是 ArrayList 实际上是一个 Object[]...所以第二个代码片段需要将原始数组复制到某个地方,然后在位置 0 处创建一个带有“0”的新数组...所以我认为第一种方法确实更好?
最佳答案
...so the 2nd code snippet will need to copy the original array to somewhere, and then create a new one with '0' at position 0...
如果当前容量有足够的空间,它就不必分配容量(使用该代码,它将使用 Oracle 的实现——只是,它的初始容量默认为 10 ).但它确实需要重新洗牌。
...so I think the first approach is indeed better?
当然,并且出于您给出的原因。第二个 block 只是不必要地使 ArrayList
在底层数组中移动内容。
(并不是说它可能很重要,除非这是在一个真正紧密的循环中运行数百万次......但仍然。)
关于java - ArrayList add() 的行为方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32123130/