正如我看到的源代码:
java.util.AbstractCollection.toArray(),它实现如下:
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
private static T[] finishToArray(T[] r, Iterator> it) {
int i = r.length;
while (it.hasNext()) {
int cap = r.length;
if (i == cap) {
int newCap = cap + (cap >> 1) + 1;
// overflow-conscious code
if (newCap - MAX_ARRAY_SIZE > 0)
newCap = hugeCapacity(cap + 1);
r = Arrays.copyOf(r, newCap);
}
r[i++] = (T)it.next();
}
// trim if overallocated
return (i == r.length) ? r : Arrays.copyOf(r, i);
}
如您所见,实现并不那么容易理解,我的问题是:
>在迭代期间,当集合的元素发生变化(大小未更改)时,我会得到什么?我想迭代器可能是某种快照.
>当集合的大小发生变化时,我会得到什么?我想知道它是否可以正常工作.