Class cast exception

W

Will

I get a Class Cast Exception at runtime with the following code, and
was wondering why this isn't allowed:

Vector v = new Vector();
//do some stuff to fill in v with a bunch of Strings
String [] s = (String [])(v.toArray());

The toArray method returns an Object [] so why can't I cast it to a
String [] if I know that everything in it will be a String? The only
workaround I've found is to make a second array and manually copy and
cast each element of the first array into the second array.
-Will
 
J

Joona I Palaste

Will said:
I get a Class Cast Exception at runtime with the following code, and
was wondering why this isn't allowed:
Vector v = new Vector();
//do some stuff to fill in v with a bunch of Strings
String [] s = (String [])(v.toArray());
The toArray method returns an Object [] so why can't I cast it to a
String [] if I know that everything in it will be a String? The only
workaround I've found is to make a second array and manually copy and
cast each element of the first array into the second array.

The Java type system doesn't work that way. If an array object's class
is Object[], you can't cast it into a String[], even if its every
element refers to a String. This is a safeguard. If you could cast it,
you would be able to have two references to the same array, one of type
Object[], another of type String[]. Now suppose you use the first
reference to put a non-String reference into the array. Then when you
access the same element through the second reference, the whole program
breaks down.
 
S

slrncalmac.2.chess

Try using String s[] = (String[])v.toArray(new String[v.size()];

By passing in an array of the type you want, toArray() will create
an array of that type; allowing the cast to work. If the passed
array is the correct size, it will use that array instead of
making a new one.

As a side note, its usually preferable to use ArrayList instead of
Vector unless you specifically need Vector.

I get a Class Cast Exception at runtime with the following code, and
was wondering why this isn't allowed:

Vector v = new Vector();
//do some stuff to fill in v with a bunch of Strings
String [] s = (String [])(v.toArray());
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

EJB Bindings - Class Cast Exception 0
Cast Exception 8
cast musings 19
Class Cast Exception and I can't figure it out 3
casting Object[] to String[] - why not? 15
How do you cast to array? 34
Tasks 1
class cast exception 1

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top