企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 将一个`Vector`的所有元素复制到另一个`Vector` > 原文: [https://beginnersbook.com/2013/12/copy-all-the-elements-of-one-vector-to-another-vector-example/](https://beginnersbook.com/2013/12/copy-all-the-elements-of-one-vector-to-another-vector-example/) 在这个例子中,我们将看到如何将`Vector`的所有元素复制到另一个`Vector`。该过程用第一向量的对应元素替换第二向量的现有元素。对于例如如果我们将向量`v1`复制到向量`v2`,那么`v2`的第一个元素将被`v1`的第一个元素替换,依此类推。 在下面的代码中,我们有两个向量`va`和`vb`和我们正在使用[`Collections.copy()`](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#copy(java.util.List, java.util.List))方法将`va`的所有元素复制到`vb`。 ### 例: ```java import java.util.Collections; import java.util.Vector; public class VectorCopyExample { public static void main(String args[]) { //First Vector of String type Vector<String> va = new Vector<String>(); //Adding elements to the first Vector va.add("AB"); va.add("BC"); va.add("CD"); va.add("DE"); //Second Vector Vector<String> vb = new Vector<String>(); //Adding elements to the second Vector vb.add("1st"); vb.add("2nd"); vb.add("3rd"); vb.add("4th"); vb.add("5th"); vb.add("6th"); /*Displaying the elements of second vector before performing the copy operation*/ System.out.println("Vector vb before copy: "+vb); //Copying all the elements of Vector va to Vector vb Collections.copy(vb, va); //Displaying elements after copy System.out.println("Vector vb after copy: "+vb); } } ``` 输出: ```java Vector vb before copy: [1st, 2nd, 3rd, 4th, 5th, 6th] Vector vb after copy: [AB, BC, CD, DE, 5th, 6th] ```