AppletTalk.com Forum Index AppletTalk.com
Java discussions newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

returning a generic array

 
Post new topic   Reply to topic    AppletTalk.com Forum Index -> comp.lang.java
View previous topic :: View next topic  
Author Message
ndac
Guest





PostPosted: Thu Mar 22, 2007 12:39 am    Post subject: returning a generic array Reply with 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
Back to top
Lew
Guest





PostPosted: Sat Mar 24, 2007 7:10 am    Post subject: Re: returning a generic array Reply with quote



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





PostPosted: Sun Mar 25, 2007 3:08 am    Post subject: Re: returning a generic array Reply with quote



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
Display posts from previous:   
Post new topic   Reply to topic    AppletTalk.com Forum Index -> comp.lang.java All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.