ClassCastException from Vector to Array

V

vhqd

hello, my trouble is exampled in the code. Please take a look and give
me some threads. thanks.

TestArray.java
//-----------------------------------------------------
import java.util.Vector;
public class TestArray {
public static void main(String[] agrs) {

// I only want to get an Array from the Vector v
Vector v = SomeClass.getVector();

// I can make sure the object type is correct
// I have checked every object in v is instanceof SomeClass
// [method1] and [method2] both throw
ClassCastException
SomeClass[] sc1 = (SomeClass[]) v.toArray(); // [method 1]
SomeClass[] sc2 = (SomeClass[]) toArray2(v); // [method 2]

// I have to code like this, and no exception any more.
Why?
SomeClass[] sc3 = new EmMessage[v.size()]; // [method 3]
for (int i = 0; i < v.size(); i++) {
sc4 = (SomeClass) v.elementAt(i);
}
}

public static Object[] toArray2(Vector vector) {
if (vector == null) {
return new Object[0];
}
Object[] obs = new Object[vector.size()];
for (int i = 0; i < obs.length; i++) {
obs = vector.elementAt(i);
}
return obs;
}

}
 
R

Richard Wheeldon

vhqd said:
SomeClass[] sc1 = (SomeClass[]) v.toArray(); // [method 1]

This will return an array of type Object[]. You can't cast an array
of type Object[] to an array of type SomeClass[] regardless of
whether every element is an instanceof SomeClass or not.

If you want to do this, you need to provide toArray an example of
the type of array you want to create.
Try:
SomeClass[] sc1 = (SomeClass[])v.toArray(new SomeClass[0]);

If you're doing this a lot, replace new SomeClass[0] with a reference
to some previously constructed array,

Richard
 
C

castillo.bryan

Note: If you allocate the right size for the array, the toArray method
will not have to allocate another array.

SomeClass[] sc1 = (SomeClass[])v.toArray(new SomeClass[v.size()]);
 
S

Stefan Schulz

Note: If you allocate the right size for the array, the toArray method
will not have to allocate another array.

SomeClass[] sc1 = (SomeClass[])v.toArray(new SomeClass[v.size()]);

It will also save a few very expensive reflection calls, so this idom is
almost always the better choice.
 

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

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,128
Latest member
ElwoodPhil
Top