Name: joT67522 Date: 01/12/98
Given a generic container class whose contents
are described in terms of Object:
class GenericValue
{
Object value;
...
}
there is no way for this class to create a deep
copy of an instance because Object.clone() cannot
be invoked on value because of the protected
attribute on clone(). Why isn't the CloneNotSupportedException sufficient protection
and Object.clone public?
This little program demonstrates the problem I am having:
racs21:: tmp 46 > cat GenericArray.java
class Int
{
int i;
Int(int j)
{
i = j;
}
int getIntValue()
{
return i;
}
void setIntValue(int j)
{
i = j;
}
public String toString()
{
return "Int="+i;
}
}
public class GenericArray
{
Object[] array;
public GenericArray(int n)
{
array = new Object[n];
}
public void insertElementAt(Object o, int n)
{
if( n >= array.length )
throw new ArrayIndexOutOfBoundsException();
array[n] = o;
}
public Object elementAt(int n)
{
if( n >= array.length )
throw new ArrayIndexOutOfBoundsException();
return array[n];
}
// Would like to make deep copy...?
public GenericArray copy()
{
GenericArray copy = new GenericArray(array.length);
for(int n = 0; n < array.length; n ++)
// copy.array[n] = array[n].clone(); this is not allowed
but should be
copy.array[n] = array[n]; // Can only make a
shallow copy
return copy;
}
public static void main(String[] args)
{
Object[] numbers = {new Int(0), new Int(1), new Int(2), new
Int(3)};
GenericArray array0 = new GenericArray(4);
for(int n = 0; n < numbers.length; n ++)
array0.insertElementAt(numbers[n], n);
// Should be able to make copy without affecting numbers[]
GenericArray array1 = array0.copy();
Int i = (Int) array1.elementAt(0);
i.setIntValue(10);
for(int n = 0; n < numbers.length; n ++)
System.out.println(n+", array1="+array1.elementAt(n)+",
numbers="+numbers[n]);
}
}
racs21:: tmp 47 > java GenericArray
0, array1=Int=10, numbers=Int=10 // The i.setIntValue(10) changed numbers[0]
1, array1=Int=1, numbers=Int=1
2, array1=Int=2, numbers=Int=2
3, array1=Int=3, numbers=Int=3
racs21:: tmp 48 >
Since I can't invoke clone() on a Object type, I cannot make an element
by element deep copy of the Object[] array. I should be able to use
the 'copy[n] = array[n].clone();' statement commented out above and
allow a class to reject this by throwing a CloneNotSupportedException.
Am I missing some obvious work around?
(Review ID: 22777)
======================================================================
- duplicates
-
JDK-4098033 Cloneable doesn't define .clone
-
- Closed
-