要避免Collections.copy的IndexOutOfBoundsException,需确保目标列表长度不小于源列表,可通过Collections.nCopies初始化目标列表;该方法为浅拷贝,修改引用对象会影响源列表;性能上为O(n),但频繁或大数据量复制时建议使用ArrayList构造函数或System.arraycopy以提升效率。

Collections.copy方法本质上是将一个列表的内容复制到另一个列表中。需要注意的是,目标列表的长度必须大于或等于源列表的长度,否则会抛出IndexOutOfBoundsException。
Collections.copy方法是Java集合框架中一个方便的工具,但用不好容易踩坑。
最常见的问题就是目标列表的大小不足以容纳源列表的内容。解决这个问题的方法很简单:在调用copy之前,确保目标列表的长度至少与源列表相同。
List<Integer> sourceList = Arrays.asList(1, 2, 3, 4, 5); List<Integer> targetList = new ArrayList<>(Collections.nCopies(sourceList.size(), 0)); // 初始化目标列表,大小与源列表相同 Collections.copy(targetList, sourceList); System.out.println(targetList); // 输出: [1, 2, 3, 4, 5]
这里使用了
Collections.nCopies
targetList
sourceList
IndexOutOfBoundsException
立即学习“Java免费学习笔记(深入)”;
Collections.copy
List<StringBuilder> sourceList = new ArrayList<>();
sourceList.add(new StringBuilder("Hello"));
sourceList.add(new StringBuilder("World"));
List<StringBuilder> targetList = new ArrayList<>(Collections.nCopies(sourceList.size(), new StringBuilder())); // 初始化目标列表
Collections.copy(targetList, sourceList);
targetList.get(0).append("!"); // 修改目标列表中的StringBuilder对象
System.out.println(sourceList.get(0)); // 输出: Hello!
System.out.println(targetList.get(0)); // 输出: Hello!可以看到,修改
targetList
StringBuilder
sourceList
Collections.copy
ArrayList
但是,如果需要频繁地复制列表,或者列表非常大,可以考虑使用其他方案,比如使用
ArrayList
System.arraycopy
// 使用ArrayList的构造函数
List<Integer> sourceList = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(sourceList);
// 使用System.arraycopy (适用于数组)
Integer[] sourceArray = {1, 2, 3, 4, 5};
Integer[] targetArray = new Integer[sourceArray.length];
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);ArrayList
System.arraycopy
Collections.copy
System.arraycopy
选择哪种方案取决于具体的使用场景和性能需求。在性能敏感的场景下,建议进行基准测试,选择最合适的方案。
以上就是Java中Collections.copy方法使用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号