Collections emptyList/singleton/singletonList/List/Set toArray

后端 未结 4 1866
轮回少年
轮回少年 2020-12-16 17:33

Suppose I have this code:

String[] left = { \"1\", \"2\" };
String[] leftNew = Collections.emptyList().toArray(left);
System.out.println(Arrays.toString(left         


        
4条回答
  •  不知归路
    2020-12-16 17:58

    Code of toArray(T[] a) of (for instance) ArrayList is quite clear:

    public  T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    

    If input array's size is bigger than this list's (which means that we can copy all the list's content into this array because it's length is big enough), then the next element reference in the array after all lists content copied (actually the index equal to the size of the list) will be set to point to null.

提交回复
热议问题