Java Collections copy()
Java Collections 类的
copy()方法将一个列表中的所有元素复制到另一个列表中。在这种方法中,目标列表的大小必须大于或等于源列表的大小。
语法
以下是
copy()方法:
public static <T> void copy(List<? super T> dest, List<? extends T> src)
参数
参数 |
说明 |
必需/可选 |
dest |
这是要在其中复制元素的目标列表。 |
必需 |
src |
这是将其元素复制到目标位置的源列表。 |
必需 |
返回
copy()方法不返回任何内容。
异常
copy()方法引发以下异常-
IndexOutOfBoundsException -引发异常如果目标列表太小而无法存储整个源列表。
UnsupportedOperationException -如果目标列表的列表迭代器不支持set操作,则抛出此类型的异常。
兼容版本
Java 1.4及更高版本
示例1
import java.util.*;
public class CollectionsCopyExample1 {
public static void main(String[] args) {
//Create lists for source and destination
List<String> srclist = new ArrayList<String>(5);
List<String> destlist = new ArrayList<String>(10);
//Populate two source and destination lists
srclist.add("Java Tutorial");
srclist.add("is best on");
srclist.add("lidihuo");
destlist.add("lidihuo");
destlist.add("is older than");
destlist.add("SSSIT");
// copy into destination list
Collections.copy(destlist, srclist);
System.out.println("Elements of source list: "+srclist);
System.out.println("Elements of destination list: "+destlist);
}
}
输出:
Elements of source list: [Java Tutorial, is best on, lidihuo]
Elements of destination list: [Java Tutorial, is best on, lidihuo]
示例2
package myPackage;
import java.util.*;
public class CollectionsCopyExample2 {
public static void main(String[] args) {
//Create lists for source and destination
List<Integer> source = Arrays.asList(1,2,3,4);
List<Integer> dest = Arrays.asList(5,6,7,8,9,10);
Collections.copy(dest, source);
//Print the List
for(Integer i : dest) {
System.out.print(i +" ");
}
}
}
输出:
示例3
import java.util.*;
public class CollectionsCopyExample3 {
public static void main(String[] args) {
//Create lists for source and destination
List<Integer> source = Arrays.asList(1,2,3,4);
List<Integer> dest = Arrays.asList(5,6,7);
Collections.copy(dest, source);
//Print the List
System.out.println(dest);
}
}
输出:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.base/java.util.Collections.copy(Collections.java:558)
at myPackage.CollectionsCopyExample3.main(CollectionsCopyExample3.java:8)
示例4
import java.util.*;
public class CollectionsCopyExample4 {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
//Create lists
ArrayList source = new ArrayList();
source.add(50);
source.add(10);
source.add(20);
System.out.println("Elements of Source List: " + source);
ArrayList dest = new ArrayList();
dest.add("one");
dest.add("two");
dest.add("three");
dest.add("four");
dest.add("five");
System.out.println("Elements of Destination List: " + dest);
Collections.copy(dest, source);
System.out.println("Elements of Destination List after copying Source List: " + dest);
}
}
输出:
Elements of Source List: [50, 10, 20]
Elements of Destination List: [one, two, three, four, five]
Elements of Destination List after copying Source List: [50, 10, 20, four, five]