Java 日历 clone()方法及示例

Java 日历 clone()方法及示例

Calendar类中的 clear() 方法是用来克隆一个日历对象的。它基本上是为这个对象创建一个浅层的副本。

语法

public Object clone()

参数: 该方法不接受任何参数。

返回值: 该方法不返回任何值。

下面的程序说明了日历类的clone()方法的工作原理:

例1 :

// Java Code to illustrate clone() Method
  
import java.util.Calendar;
  
public class CalendarClassDemo {
    public static void main(String args[])
    {
        // Creating a calendar object
        Calendar calndr1 = Calendar.getInstance();
  
        // Displaying current calendar
        System.out.println("Original calendar: "
                           + calndr1.getTime());
  
        // Cloning the original
        Calendar calndr2 = (Calendar)calndr1.clone();
  
        // Displaying the Copy
        System.out.println("Cloned calendar: "
                           + calndr2.getTime());
    }
}

输出:

Original calendar: Tue Feb 12 11:41:36 UTC 2019
Cloned calendar: Tue Feb 12 11:41:36 UTC 2019

例2 :

// Java Code to illustrate clone() Method
  
import java.util.*;
  
public class CalendarClassDemo {
    public static void main(String args[])
    {
        // Creating a calendar object
        Calendar calndr1
            = new GregorianCalendar(2018, 12, 2);
  
        // Displaying current calendar
        System.out.println("Original calendar: "
                           + calndr1.getTime());
  
        // Cloning the original
        Calendar calndr2 = (Calendar)calndr1.clone();
  
        // Displaying the Copy
        System.out.println("Cloned calendar: "
                           + calndr2.getTime());
    }
}

输出:

Original calendar: Wed Jan 02 00:00:00 UTC 2019
Cloned calendar: Wed Jan 02 00:00:00 UTC 2019

**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clone()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程