当前位置: 代码迷 >> J2SE >> 关于Collections的copy会合运行时报错,下标越界,求解
  详细解决方案

关于Collections的copy会合运行时报错,下标越界,求解

热度:34   发布时间:2016-04-23 20:32:22.0
关于Collections的copy集合运行时报错,下标越界,求解
package chart07;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class TestCollections {
public static void main(String[] args) {
List<String> l1 = new LinkedList<String>();
List<String> l2 = new LinkedList<String>();

for (int i = 0; i <= 9; i++) {
l1.add("a" + i);
}


Collections.copy(l2, l1);
System.out.println(l1);
System.out.println(l2);

}
}

抛异常如下:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Collections.java:529)
at chart07.TestCollections.main(TestCollections.java:17)

------解决方案--------------------
在copy方法调用之前打印一下就知道了;


System.out.println(l1.size());
System.out.println(l2.size());

------解决方案--------------------
可以用addAll方法;

List<String> l1 = new LinkedList<String>();
List<String> l2 = new LinkedList<String>();

for (int i = 0; i <= 9; i++)
{
l1.add("a" + i);
}

l2.addAll(l1);

System.out.println(l1.size());
System.out.println(l2.size());
Collections.copy(l2, l1);
System.out.println(l1);
System.out.println(l2);
  相关解决方案