当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.util.ArrayList.clone()用法及代码示例



描述

这个java.util.ArrayList.clone()返回这个 ArrayList 实例的浅拷贝(即元素本身不被复制)。

声明

以下是声明java.util.ArrayList.clone()方法

public Object clone()

参数

NA

返回值

此方法返回此 ArrayList 实例的副本。

异常

NA

示例

下面的例子展示了 java.util.Arraylist.clone() 方法的用法。

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String args[]) {

      // create an empty array list
      ArrayList<StringBuilder> arrlist1 = new ArrayList<StringBuilder>();

      // use add for new value
      arrlist1.add(new StringBuilder("Learning-"));

      // using clone to affect the objects pointed to by the references.
      ArrayList arrlist2 = (ArrayList) arrlist1.clone();

      // appending the string
      StringBuilder strbuilder = arrlist1.get(0);
      strbuilder.append("list1, list2-both pointing to the same StringBuilder");

      System.out.println("The 1st list prints:");

      // both lists will print the same value, printing list1
      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:");

      // both lists will print the same value, printing list2
      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

相关用法


注:本文由纯净天空筛选整理自 Java.util.ArrayList.clone() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。