如何复制或克隆一个 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-02-25

1K+ 查看

开启你的职业生涯

通过完成课程获得认证

开始吧
广告