| View previous topic :: View next topic |
| Author |
Message |
ndac Guest
|
Posted: Thu Mar 22, 2007 12:39 am Post subject: returning a generic array |
|
|
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 |
|
| Back to top |
|
 |
Lew Guest
|
Posted: Sat Mar 24, 2007 7:10 am Post subject: Re: returning a generic array |
|
|
ndac wrote:
| Quote: | 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?
|
Arrays and generics don't play well together.
-- Lew |
|
| Back to top |
|
 |
Alex Gout Guest
|
Posted: Sun Mar 25, 2007 3:08 am Post subject: Re: returning a generic array |
|
|
ndac schreef:
| Quote: | 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
|
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. |
|
| Back to top |
|
 |
|