JDK的Collection.toArray(T a)的替代实现

时间:2017-11-15 20:19:09

标签: java arrays performance collections readability

浏览一些JDK源代码我在Collection.toArray()中找到了toArray(T[])AbstractCollection的以下实现:

public Object[] toArray() {
    // Estimate size of array; be prepared to see more or fewer elements
    Object[] r = new Object[size()];
    Iterator<E> 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;
}

public <T> T[] toArray(T[] a) {
    // Estimate size of array; be prepared to see more or fewer elements
    int size = size();
    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) {
                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 final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

@SuppressWarnings("unchecked")
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 + (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);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError
            ("Required array size too large");
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

但是,由于我现在'默认实现'一个Collection - 接口,我想知道这些方法的实现是否不能简化为可读性如下,没有更多的迭代,数组创建或通常更差的性能:

@Override
default Object[] toArray() {
    Object[] result = new Object[size()];
    Iterator<E> it = iterator();
    int i = 0;
    while (it.hasNext()) {
        if (i == result.length) // more objects than expected, resize
            result = Arrays.copyOf(result, newSize(i));
        result[i++] = it.next();
    }
    if (i != result.length) // trim array
        result = Arrays.copyOf(result, i);
    return result;
}

@Override
default <T> T[] toArray(T[] a) {
    int size = size();
    T[] result = size > a.length ? (T[]) Array.newInstance(a.getClass().getComponentType(), size) : a;
    Iterator<E> it = iterator();
    int i = 0;
    while (it.hasNext()) {
        if (i == result.length) // more objects than expected, resize
            result = Arrays.copyOf(result, newSize(i));
        result[i++] = (T) it.next();
    }
    if (i != result.length)
        if (result == a) // set next element to null
            a[i] = null;
        else // trim array
            result = Arrays.copyOf(result, i);
    return result;
}

private static int newSize(int currentSize) {
    if (currentSize == Integer.MAX_VALUE)
        throw new OutOfMemoryError("Required array size too large");
    int newSize = currentSize + (currentSize >> 1) + 1;
    if (newSize < 0)
        // overflow - exceed MAX_ARRAY_SIZE from AbstractCollection only if inevitable
        return Math.max(Integer.MAX_VALUE - 8, currentSize + 1);
    // clip at MAX_ARRAY_SIZE from AbstractCollection
    return Math.min(newSize, Integer.MAX_VALUE - 8);
}

我知道'简化'总是在某种程度上是主观的,但我是 特别是指在JDK实现中调用finishToArray(T[], Iterator<?>)时的许多级别的缩进和第二步思考,也许你明白了。

由于这段代码是由Neal Gafter和Joshua Bloch编写的,因此我可以更好地调用我的解决方案,因此我希望得到您的反馈。 另外我的代码没有经过测试,所以如果你发现一些导致bug的特殊情况,我也想知道它们。

修改,因为已经请求了有关已更改内容的详细说明:
简化的要点是使用Collection {{1}将for循环从0循环到r.length(初始size())到while循环因此,当实际上没有剩余元素时,循环才结束,从而使Iterator方法不必要。
finishToArray(..)的{​​{1}}循环中相当复杂的主体已经从几个toArray(T[] a)分支高度简化 - 包括for语句到一个简单的if - 分支必要时调整数组大小。

这就是为什么我想知道JDK实现是否提供了某种优势,或者我的某种方式是否错误以及我没有想过的方式。

0 个答案:

没有答案
相关问题