pnelnik
2010-03-30 01:31:55 UTC
But how can I make a deep copy?
In the example below, what I would like to happen is:
- I assign d2 to d1,
- then update d1, but find that d2 is unaffected.
But what I find is that d2 is affected,
since the assignment was just adding a reference (shallow copy)
rather than a deep copy which is what I want.
/////////////////////////////////////////////////////////////////////////////
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
class Test4
{
public static void main(String[] args)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = formatter.parse("1980-10-10");
Date d2;
d2 = d1; // adds a reference to d1
d1.setMonth(4); // set d1 to May ( I know setMonth(..) is deprecated but ...)
System.out.println("d2 " + d2); // we find d2 is now also May
}
catch (Exception e)
{ // Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
} // end of method: main(..)
} // end of class Test4
/////////////////////////////////////////////////////////////////////////////
I tried the following:
d2 = new Date(d1); // no such constructor
and d2 = d1.clone(); // incompatible types, found: java.lang.Object, required: java.util.Date
But neither compiled.