Original Post
As I just learned, cloning in Java can't be achieved by using a "copy constructor". You have to implement the Interface Cloneable instead and call super.clone() in your own clone() method for a shallow copy. After that, you must take whatever steps necessary to make a deep copy (if that is the desired behavior). As I've never done this before I post the clone() methods of two of my classes and would ask you to check if I got this right: shallow copy of two int values: array has to be copied to get a deep copy, rest is shallow: Is there any way to get rid of these nasty typecasts? I thought I would have gotten rid of them at last with the introduction of generics.
public class Slice implements Cloneable
{
private int _bot;
private int _top;
[...]
public Object clone()
{
Slice that = null;
try
{
that = (Slice) super.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
System.exit(-1);
}
return that;
}
}
public class Piece implements Cloneable
{
private Slice[] _slice;
private int _capacity;
private int _left;
private int _right;
[...]
public Object clone()
{
assert isReduced() : "Vorbedingung verletzt: isReduced()";
Piece that = null;
try
{
that = (Piece) super.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
System.exit(-1);
}
that._slice = new Slice[_capacity];
for (int i=_left; i<_right; i++)
{
that._slice = (Slice) _slice.clone();
}
assert that.isReduced() : "Nachbedingung verletzt: result.isReduced()";
return that;
}
}