Collections.copy源码解析

在使用java.util.copy过程中发现总是出现异常错误,后来查看源码后,发现在使用之前,需要手动的开辟空间为要拷贝的数据,因为自己的使用不当,导致错误

使用方式:

  1. List asList = Arrays.asList(new String[src.size()]);
  2. new ArrayList() ,Collections.addAll(dest, new Object[src.size()] , Collections.copy(dest, src)

源码解析:

public static  void copy(List dest, List src) {
        int srcSize = src.size(); //首先获取src的个数
        if (srcSize > dest.size())//如果要拷贝的个数大于大于dest的个数,抛出异常
            throw new IndexOutOfBoundsException("Source does not fit in dest");
        //RandomAccess是一个空接口,起到标识作用,支持随机访问方式
        if (srcSize < COPY_THRESHOLD ||
            (src instanceof RandomAccess && dest instanceof RandomAccess)) {
            for (int i=0; i di=dest.listIterator();
            ListIterator si=src.listIterator();
            for (int i=0; i

你可能感兴趣的:(Java)