如何复制或克隆 Java ArrayList?


 java.util.ArrayList 类的 clone() 方法返回此 ArrayList 实例的浅表副本(即,元素本身不会复制)。通过使用此方法,你可以将一个数组列表的内容复制到另一个数组列表。

示例

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String args[]) {
      ArrayList<StringBuilder> arrlist1 = new ArrayList<StringBuilder>();
      arrlist1.add(new StringBuilder("Learning-"));
      ArrayList arrlist2 = (ArrayList) arrlist1.clone();
      StringBuilder strbuilder = arrlist1.get(0);
      strbuilder.append("list1, list2-both pointing to the same StringBuilder");
      System.out.println("The 1st list prints: ");
      for (int i = 0; i < arrlist1.size(); i++) {
         System.out.print(arrlist1.get(i) + " ");
      }
      System.out.println("The 2nd list prints the same i.e:");
      for (int i = 0; i < arrlist2.size(); i++) {
         System.out.print(arrlist2.get(i));
      }
   }
}

输出

The 1st list prints:
Learning-list1, list2 - both pointing to the same StringBuilder
The 2nd list prints the same i.e:
Learning-list1, list2 - both pointing to the same StringBuilder

更新于:2020 年 2 月 25 日

1K+ 阅读

启动您的 职业

完成课程获得认证

开始
广告