Java Object clone() 方法



描述

Java Object clone() 方法建立一個並返回此物件的副本。 “副本”的確切含義可能取決於物件的類。總體意圖是,對於任何物件 x,表示式:

 x.clone() != x

將為真,並且表示式:

x.clone().getClass() == x.getClass()

將為真,但這些並非絕對要求。雖然通常情況下:

 x.clone().equals(x)

為真,但這並非絕對要求。

宣告

以下是java.lang.Object.clone() 方法的宣告

protected Object clone()

引數

返回值

此方法返回此例項的克隆。

異常

CloneNotSupportedException −如果物件的類不支援 Cloneable 介面。覆蓋 clone 方法的子類也可以丟擲此異常以指示無法克隆例項。

獲取 GregorianCalendar 物件克隆示例

以下示例顯示了 java.lang.Object.clone() 方法的使用。在這個程式中,我們建立了一個 GregorianCalendar 例項,然後使用 clone() 方法,我們使用之前的物件建立了另一個物件。列印了兩個物件的時間。

package com.tutorialspoint;

import java.util.GregorianCalendar;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a gregorian calendar, which is an object
      GregorianCalendar cal = new GregorianCalendar();

      // clone object cal into object y
      GregorianCalendar y = (GregorianCalendar) cal.clone();

      // print both cal and y
      System.out.println(cal.getTime());
      System.out.println(y.getTime());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Fri May 31 13:50:19 IST 2024
Fri May 31 13:50:19 IST 2024

獲取 ArrayList 物件克隆示例

以下示例顯示了 java.lang.Object.clone() 方法的使用。在這個程式中,我們建立了一個 ArrayList 例項,然後使用 clone() 方法,我們使用之前的物件建立了另一個物件。列印了兩個物件。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class ObjectDemo {

  public static void main(String[] args) {

    // create a ArrayList, which is an object
    ArrayList<String> list = new ArrayList<>();

    // add value to the list
    list.add("Tutorialspoint");

    // clone object list into object y
    List<String> y = (List) list.clone();
  
    // print both list and y
    System.out.println(list);
    System.out.println(y);
  }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

[Tutorialspoint]
[Tutorialspoint]

獲取 HashMap 物件克隆示例

以下示例顯示了 java.lang.Object.clone() 方法的使用。在這個程式中,我們建立了一個 HashMap 例項,然後使用 clone() 方法,我們使用之前的物件建立了另一個物件。列印了兩個物件。

package com.tutorialspoint;

import java.util.HashMap;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a HashMap, which is an object
      HashMap<String, String> map = new HashMap<>();

      // add a value to the map
      map.put("t", "tutorialspoint");
      
      // clone object map into object y
      HashMap<String, String> y = (HashMap)map.clone();

      // print both map and y
      System.out.println(map);
      System.out.println(y);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

{t=tutorialspoint}
{t=tutorialspoint}
java_lang_object.htm
廣告
© . All rights reserved.