Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic arrays

 
Olivier Legat
Ranch Hand
Posts: 176
Chrome Mac Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy fellow coders,

I have a question about generic arrays. I have this function.

Which compiles when placed in a my ArrayUtil class. However whenever I use it I get an exception.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.StackTraceElement;

This is probably because of my (T[]) cast. The compiler won't let me create a generic array T. So how can I fix this problem?

Thanks in advance.
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Check this out.
Check method -
I think you also need to pass another param to mention what type of array you are handling.

Regards,
amit
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Olivier,

Please, TellTheDetails (i.e. exactly when you are having this exception).

It took me a little type to figure this out that the exception occurs when you actually try to assign output of subset method to an array

As amit has suggested, either you should provide class type of T to the method (which will return the array of type T, instead of array of Object), or, you have to get the returned value in an Object array, and later-on you can cast it to real type T.

HIH.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic