"ndac" <nd**@ndac.comwrote in message
news:46***********************@news.sunsite.dk...
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<Stringx = new X<String>();
...
String[] a = x.toArray();
(or String[] a = (String[])x.toArray();)
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.