Overriding clone() in Java 5 (with generics)?


U

Ulrich Hobelmann

Hi, is there any way I can have a typesafe clone() in Java 5?

I have a subclass of LinkedList<T>, but calling clone() causes warnings,
and typecasting to (MyList<T>) doesn't work either.

I overrode public MyList<T> clone() in my list class, but calling
super.clone() again caused the same problem, so there's no way out ;)

How do you make clone() typesafe (or typesafely call it), and compile
without complaints? As I only made some minor modifications to
LinkedList, I basically refuse to write my own clone() (say, with addAll()).
 
Ad

Advertisements

H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ulrich Hobelmann schreef:
Hi, is there any way I can have a typesafe clone() in Java 5?

I have a subclass of LinkedList<T>, but calling clone() causes warnings,
and typecasting to (MyList<T>) doesn't work either.

I overrode public MyList<T> clone() in my list class, but calling
super.clone() again caused the same problem, so there's no way out ;)

How do you make clone() typesafe (or typesafely call it), and compile
without complaints? As I only made some minor modifications to
LinkedList, I basically refuse to write my own clone() (say, with
addAll()).

Unfortunately, the java.util classes did not use the covariant return
possibility in Java 5 and reimplemented clone(). The problem is
backwards compatibility: subclasses would have to be reimplemented as
well. So you’ll have to use @SuppressWarnings("unchecked") if you want
to get rid of the warning.

H.

- --
Hendrik Maryns

==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFEv6iGe+7xMGD3itQRAnNxAJ4+KcamBIYJUMNFZafAAGqIkOGElgCfbktA
kCNfo1Dpvji0dpcUw1J06gk=
=mE8y
-----END PGP SIGNATURE-----
 

Top