Click to See Complete Forum and Search --> : problem casting Collection


stephen fischer
September 20th, 2000, 10:16 PM
this causes a ClassCastException:

ArrayList al = new ArrayList();
al.add(new String("Adam"));
al.add(new String("Bob"));
al.add(new String("Carl"));

String sl[] = (String [])al.toArray();

does anyone know how to make this cast work?

Phill
September 20th, 2000, 11:22 PM
Hi there
That method returns an Object array.
The problem with this is that there is no
way to cast an array of one type to an array
of another type.
You have to cast each individual element of the
array to another type and place it in the
appropriate array.
One way to do this is :
in the following loop, there is supposed to
be an array index i after the str variable.


ArrayList al = new ArrayList();
al.add(new String("Adam"));
al.add(new String("Bob"));
al.add(new String("Carl"));
String[] str = new String[al.size()];
for(int i = 0; i < al.size(); i++){
str[i] = (String)al.get(i);
System.out.println(str[i]);
}



Phill.