All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jet.runtime.CollectionToArray Maven / Gradle / Ivy

There is a newer version: 2.1.0-Beta1
Show newest version
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[] toArray(Collection 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 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[] 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() {
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy