Re: Generics warning message.



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-----
.



Relevant Pages

  • Re: Generics warning message.
    ... External Concepts Guild wrote: ... The code compiles without ... warnings or errors and it runs correctly. ... That's not a cast, that's a copy. ...
    (comp.lang.java.programmer)
  • Re: void * vs char *
    ... That doesn't mean never cast, but it does mean that if the compiler is warning you, you should generally assume it's right. ... and not some optional lint tool to pick through my code for places ... If you don't like your compiler being helpful, either turn off or ignore the warnings. ...
    (comp.lang.c)
  • Re: shame on MISRA
    ... of warnings about "explicit cast required" for assignments and ... with a cast. ... GCC with no warnings. ...
    (comp.arch.embedded)
  • Re: Generics and ClassLoaders
    ... to Classless so - after all I am explicitly casting. ... It's unfortunately not really possible to develop with generics and warnings for unchecked casts enabled, without just ignoring certain compiler warnings. ... I've returned to just using Classand using a cast at newInstance. ...
    (comp.lang.java.programmer)
  • Re: Type-casting void pointers?
    ... There are some lousy compilers out there. ... delivering code with hundreds of warnings is not good for business). ... The cast, where it is obvious, can also be used as documentation: ...
    (comp.lang.c)