T
tamas.hauer
Hi,
I am trying to deep-copy a complex data type. To that end I
implemented clone() for all the types involved and I am having problems
with generics. It's much harder to explain than to show, thus let me
show a silly example which demonstrates it:
class Super implements Cloneable {
public Super clone() {
return new Super();
}
}
class Sub extends Super {
public Sub clone() {
return new Sub();
}
}
public <T extends Super> void test( T item ){
java.util.HashSet<T> set = new java.util.HashSet<T>( );
set.add( item.clone() ); // <<<<<<< ERROR
}
I understand the error, as the compiler thinks item.clone() returns
'Super' instead of 'T'. I can do a cast to 'T': set.add(
(T)(item.clone()) ); which works allright but gives me an unchecked
cast understandably.
So my question is: is there a better way to declare this clone() method
so that it can be used in generic contexts with <T extends super>, and
if there is no such thing, is there a way to get rid of the unchecked
cast warning just for this piece of code (without turning it off for
the whole file)?
Thanks,
Tamas
I am trying to deep-copy a complex data type. To that end I
implemented clone() for all the types involved and I am having problems
with generics. It's much harder to explain than to show, thus let me
show a silly example which demonstrates it:
class Super implements Cloneable {
public Super clone() {
return new Super();
}
}
class Sub extends Super {
public Sub clone() {
return new Sub();
}
}
public <T extends Super> void test( T item ){
java.util.HashSet<T> set = new java.util.HashSet<T>( );
set.add( item.clone() ); // <<<<<<< ERROR
}
I understand the error, as the compiler thinks item.clone() returns
'Super' instead of 'T'. I can do a cast to 'T': set.add(
(T)(item.clone()) ); which works allright but gives me an unchecked
cast understandably.
So my question is: is there a better way to declare this clone() method
so that it can be used in generic contexts with <T extends super>, and
if there is no such thing, is there a way to get rid of the unchecked
cast warning just for this piece of code (without turning it off for
the whole file)?
Thanks,
Tamas