Re: Generics warning message.
- From: External Concepts Guild <REE9opdZ@xxxxxxxxx>
- Date: Mon, 31 Dec 2007 08:07:29 -0800 (PST)
On Dec 30, 8:12 pm, Lew <l...@xxxxxxxxxxxxx> wrote:
External Concepts Guild wrote:
There might be a way. I think the following code performs a similar
function to what you are trying to achieve. The code compiles without
warnings or errors and it runs correctly. Nonetheless, it leaves
something to be desired.
private static < R > ArrayList < R > nowarningCast
( Class < R > clazz , ArrayList in )
{
ArrayList < R > out = new ArrayList < R > ( ) ;
for ( Object val : in )
{
R r = clazz . cast ( val ) ;
out . add ( r ) ;
}
return ( out ) ;
}
}
That's not a cast, that's a copy. But I'll bet you could do a cast with a
Class<ArrayList<R>> with a similar idiom.
--
Lew
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
You are absolutely correct: it is a copy not a cast. I believe that
because of the nature of type erasure <http://java.sun.com/docs/books/
tutorial/java/generics/erasure.html> it is impossible to do a cast
(without at least generating a warning). Thus to achieve the effect
that the OP desires, it is necessary to cheat (e.g. copying rather
than casting).
If you have control of the writing operation as well as the reading,
then you could solve this problem by using a nonparameterized
extension of ArrayList<R>. For example, consider class MyArrayList
extends ArrayList<String> { }. If you wrote a MyArrayList, then you
should be able to read it and cast it without warnings.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
iD8DBQFHeRMOVQdj5Q2e9q0RAnhKAJ0ZEYpep1as38WX0VcLwORMP/+AkACfYoSG
KBxX6RsV4q17sFOg3muG0Og=
=i8ZY
-----END PGP SIGNATURE-----
.
- Follow-Ups:
- Re: Generics warning message.
- From: Zig
- Re: Generics warning message.
- References:
- Generics warning message.
- From: Roedy Green
- Re: Generics warning message.
- From: External Concepts Guild
- Re: Generics warning message.
- From: Lew
- Generics warning message.
- Prev by Date: Re: the MI 5 spammer
- Next by Date: Re: How to tie
- Previous by thread: Re: Generics warning message.
- Next by thread: Re: Generics warning message.
- Index(es):
Relevant Pages
|