Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4028518

clone() method in java.util.Calendar not working properly

XMLWordPrintable

    • 1.2beta3
    • sparc
    • solaris_2.5
    • Not verified



      Name: mc57594 Date: 01/28/97


      When modifying a cloned object instance that extends
        Calendar (e.g. GregorianCalendar), those modifications will also
        be reflected in the original object instance. Could this be an
        example of shallow cloning? Example to follow:

      import java.util.GregorianCalendar ;

      public class CalendarBug {

         public static void main(String[] args)
         {
            GregorianCalendar cal1 = new GregorianCalendar() ;
            GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ;

            printdate(cal1, "cal1: ") ;
            printdate(cal2, "cal2 - cloned(): ") ;
            cal2.add(GregorianCalendar.DATE, 1) ;
            printdate(cal1, "cal1 after adding 1 day:") ;
            printdate(cal2, "cal2 should be unmodified:") ;
         }

         private static void printdate(GregorianCalendar cal, String string)
         {
            System.out.print(string);
            System.out.print("" + cal.get(GregorianCalendar.MONTH)) ;
            int date = cal.get(GregorianCalendar.DATE) + 1 ;
            System.out.print("/" + date) ;
            System.out.println("/" + cal.get(GregorianCalendar.YEAR)) ;
         }
      }
      ======================================================================

            joconnersunw John Oconner (Inactive)
            mchamnessunw Mark Chamness (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: