Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:如何为集合实现toArray`_Java_Collections_Types_Casting_Toarray - Fatal编程技术网

Java:如何为集合实现toArray`

Java:如何为集合实现toArray`,java,collections,types,casting,toarray,Java,Collections,Types,Casting,Toarray,现在,我有: public <T> T[] toArray(T[] old) { T[] arr = Arrays.copyOf(old, old.length + size()); int i = old.length; for(E obj : this) { arr[i] = old.getClass().getComponentType().cast(obj); ++i;

现在,我有:

    public <T> T[] toArray(T[] old) {
        T[] arr = Arrays.copyOf(old, old.length + size());
        int i = old.length;
        for(E obj : this) {
            arr[i] = old.getClass().getComponentType().cast(obj);
            ++i;
        }
        return arr;
    }
这仍然是实现它的最佳/最直接的方法吗?我能在没有警告的情况下以某种方式编码它吗?否则我将如何实现它


编辑:我当前的解决方案。首先,我真的不想在
toArray
中出现这样的警告。因此,我对这些小助手函数进行了编码(以便进一步讨论):

这仍然是实现它的最佳/最直接的方法吗?否则我将如何实现它

乔希·布洛赫不是这样做的。看一看这个问题的根源。以下是JDK1.6.0_22中的相关性摘录

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[]) 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)
                return Arrays.copyOf(r, i);
            r[i] = null; // null-terminate
            return r;
        }
        r[i] = (T) it.next();
    }
    return it.hasNext() ? finishToArray(r, it) : r;
}
public T[]toArray(T[]a){
//估计数组的大小;准备查看更多或更少的元素
int size=size();
T[]r=a.长度>=尺寸
A.
:(T[])Array.newInstance(a.getClass().getComponentType(),size);
迭代器it=迭代器();
对于(int i=0;i
源代码位于JDK的
src.zip
文件中。您可以将它集成到任何像样的IDE中,如Eclipse/IDEA/Netbeans,以便在打开
AbstractCollection
类时可以看到它

我能在没有警告的情况下以某种方式编码它吗

不可以。如果它困扰您,请使用
@SuppressWarnings(“未选中”)


也就是说,如果可能的话,我建议扩展
AbstractCollection
而不是实现
Collection
,这样您至少已经实现了基本功能。

首先,如果它应该是
Collection.toArray()的实现,它不符合约定-不应在数组中保留旧元素(请参阅)

正确的实现如下所示:

public <T> T[] toArray(T[] array) { 
    int size = size();
    if (array.length < size) { 
        // If array is too small, allocate the new one with the same component type
        array = Array.newInstance(array.getClass().getComponentType(), size);
    } else if (array.length > size) {
        // If array is to large, set the first unassigned element to null
        array[size] = null;
    }

    int i = 0;
    for (E e: this) {
        // No need for checked cast - ArrayStoreException will be thrown 
        // if types are incompatible, just as required
        array[i] = (T) e;
        i++;
    }
    return array;
} 
public T[]到数组(T[]数组){
int size=size();
如果(array.lengthsize){
//如果数组太大,则将第一个未赋值元素设置为null
数组[size]=null;
}
int i=0;
对于(E:本){
//不需要选中强制转换-将引发ArrayStoreException
//如果类型不兼容,请按要求执行
数组[i]=(T)e;
i++;
}
返回数组;
} 

您想在签名中的某个位置创建一个集合吗?您所能做的就是将其强制转换为(T),cast()方法只会更改引用的类型,而不会更改被引用对象的类型。谢谢您的提示。因为,我没有可用的Javadoc,也懒得在网上搜索它。:)
    public <T> T[] toArray(T[] array) { 
        int size = size();
        if (array.length < size) { 
            array = newArray(classOf(array), size);
        } else if (array.length > size) {
            array[size] = null;
        }

        int i = 0;
        for (E e : this) {
            array[i] = classOf(array).cast(e);
            i++;
        }
        return array;
    } 
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[]) 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)
                return Arrays.copyOf(r, i);
            r[i] = null; // null-terminate
            return r;
        }
        r[i] = (T) it.next();
    }
    return it.hasNext() ? finishToArray(r, it) : r;
}
public <T> T[] toArray(T[] array) { 
    int size = size();
    if (array.length < size) { 
        // If array is too small, allocate the new one with the same component type
        array = Array.newInstance(array.getClass().getComponentType(), size);
    } else if (array.length > size) {
        // If array is to large, set the first unassigned element to null
        array[size] = null;
    }

    int i = 0;
    for (E e: this) {
        // No need for checked cast - ArrayStoreException will be thrown 
        // if types are incompatible, just as required
        array[i] = (T) e;
        i++;
    }
    return array;
}