Generated default implementations for Collection.toArray().
#KT-3352 in progress
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package jet.runtime;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
|
||||
public class CollectionToArray {
|
||||
// Implementation copied from AbstractCollection
|
||||
|
||||
public static Object[] toArray(Collection<?> collection) {
|
||||
Object[] r = new Object[collection.size()];
|
||||
Iterator<?> it = collection.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;
|
||||
}
|
||||
|
||||
public static <T, E> T[] toArray(Collection<E> collection, T[] a) {
|
||||
// Estimate size of array; be prepared to see more or fewer elements
|
||||
int size = collection.size();
|
||||
T[] r = a.length >= size ? a :
|
||||
(T[])java.lang.reflect.Array
|
||||
.newInstance(a.getClass().getComponentType(), size);
|
||||
Iterator<E> it = collection.iterator();
|
||||
|
||||
for (int i = 0; i < r.length; i++) {
|
||||
if (! it.hasNext()) { // fewer elements than expected
|
||||
if (a != r)
|
||||
return Arrays.copyOf(r, i);
|
||||
r[i] = null; // null-terminate
|
||||
return r;
|
||||
}
|
||||
r[i] = (T)it.next();
|
||||
}
|
||||
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) {
|
||||
int newCap = ((cap / 2) + 1) * 3;
|
||||
if (newCap <= cap) { // integer overflow
|
||||
if (cap == Integer.MAX_VALUE)
|
||||
throw new OutOfMemoryError
|
||||
("Required array size too large");
|
||||
newCap = Integer.MAX_VALUE;
|
||||
}
|
||||
r = Arrays.copyOf(r, newCap);
|
||||
}
|
||||
r[i++] = (T)it.next();
|
||||
}
|
||||
// trim if overallocated
|
||||
return (i == r.length) ? r : Arrays.copyOf(r, i);
|
||||
}
|
||||
|
||||
private CollectionToArray() {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user