my dog learned polymorphism
The moose likes Java in General and the fly likes Generic arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic arrays" Watch "Generic arrays" New topic

Generic arrays

Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

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

Joined: May 14, 2004
Posts: 544
Check this out.
Check method -
I think you also need to pass another param to mention what type of array you are handling.

Anayonkar Shivalkar

Joined: Dec 08, 2010
Posts: 1545

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.


Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
I agree. Here's the link:
subject: Generic arrays
It's not a secret anymore!