位置:首頁 > Java技術 > Java.util包 > Java.util.ArrayList.clone()方法實例

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.yiibai;

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