Publicobject[] ToArray () {//To an array, and consider the case where other threads delete collection elements and insert data to collection when the method is executedObject[] R =Newobject[size ()]; Iterator<E> it =iterator (); for(inti = 0; i < r.length; i++) { if(! It.hasnext ())//when the method is called by the current thread, another thread calls This.remove or Iterator.remove returnarrays.copyof (R, I); The length of the returned array is I, which is the actual size r[i]=It.next (); }
// When the method is called by the current thread, the other thread calls This.add or Iterator.add, and It.hasnext is true to execute finishtoarray when no other thread calls add ( Iterator.add), remove (Iterator.remove), returns R
return it.hasnext ()?
}
Writes the result of the execution toarray to the passed parameter.
Public <T> t[] ToArray (t[] a) {
int size = size ();
If the parameter array length >=collection capacity, return the parameter array, otherwise return the new Java.lang.reflect.Array, the size of collection itself capacity
T[] r = a.length >= size? A:
(t[]) Java.lang.reflect.Array
. newinstance (A.getclass (). Getcomponenttype (), size);
Iterator<e> it = Iterator ();
for (int i = 0; i < r.length; i++) {
if (! It.hasnext ()) {//fewer elements than expected
if (a = = r) { //when the parameter array length >=collection capacity
R[i] = null; Null-terminate
} else if (A.length < i) {
Return arrays.copyof (R, I);
} else {
System.arraycopy (r, 0, a, 0, i);
if (A.length > i) {
A[i] = null;
}
}
return A;
}
R[i] = (T) it.next ();
}
More elements than expected
Return It.hasnext ()? Finishtoarray (R, it): R;
}
private static <T> t[] Finishtoarray (t[] R, iterator<?> it) {
int i = r.length;
while (It.hasnext ()) {
int cap = R.length;
if (i = = cap) {
Each time the index value points to the last element of the array + 1 o'clock expands by the speed of 1-bit +1 to the right, such as 11 expansion into 11+11/2+1=17
When the ArrayList Add method is executed, when the array length is insufficient, the speed of the 1-bit is shifted to the right to expand, such as 11 capacity to 11+11/2=16
When executing ToArray, why add 1, I do not quite understand??????
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 (); Because at the beginning of I the value is r.length, so i++ instead of ++i
}
To improve efficiency, when the while execution completes, if the index value is exactly at the end of the array + 1 o'clock, directly return R
actually return (i! = r.length? Arrays.copyof (R, i): R) is more efficient because the i==r.length situation is very state, especially when the array is large
return (i = = r.length)? R:arrays.copyof (R, I);
}
Java.util Source code abstractcollection (based on jdk1.7)