Hello,
assume I have the following:
public interface X<E> {
...
E[] toArray();
}
public class XImp<E> {
E[] toArray(){
E[] a = (E[])new Object[N];
...
return a;
}
}
using this like this gives me a bad cast exception?
X<String> x = new X<String>();
...
String[] a = x.toArray();
(or String[] a = (String[])x.toArray();)
what am I doing wrong here?
Regards
Lew - 24 Mar 2007 04:46 GMT
> Hello,
>
[quoted text clipped - 19 lines]
>
> what am I doing wrong here?
Arrays and generics don't play well together.
-- Lew
Alex Gout - 24 Mar 2007 23:08 GMT
ndac schreef:
> Hello,
>
[quoted text clipped - 21 lines]
>
> Regards
You cannot just cast an object array to another type array. It's not
just because you use generics, it's just the way arrays work.
jupiter - 28 May 2007 18:54 GMT
> Hello,
>
[quoted text clipped - 19 lines]
>
> what am I doing wrong here?
Don't forget: .toArray() must return Object[]. It would be nice to
be able to cast from Object[] to String[] but you can't.
You can cast the items though after storing them in Object[]
though.
Object[] obj = x.toArray();
String[] str = null;
str[0] = (String)obj[0];
Of course the cast could be wrong at runtime. You have to make
sure that all the objects in obj can be represented by String.
Seems to me that it would be nice to have .toArray() return the
correct type someday. But even if the cast you tried to do would
work, you'd still have the same problem at runtime if one of the
objects was not capable of being represented by String. I don't
think it's a trivial fix.