Posted By:
Francis_Wong
Posted On:
Wednesday, April 7, 2004 02:07 PM
Pathios - Try this code snippet:
--------------------
Collection c = new ArrayList();
c.add("John Smith");
c.add("Mary Smith");
// The next line will cause an ArrayStoreException
// c.add(new Integer(5));
// The next line will cause a ClassCastException
// String[] myList = (String [])c.toArray();
String[] myList = (String [])c.toArray(new String[c.size()]);
for (int i=0; i < myList.length; i++) {
System.out.println(myList[i]);
}
----------------------
It seems like this is overkill, and the following line should have worked just
fine:
String[] myList = (String [])c.toArray()
But Java doesn't allow an Object[] array to be cast as a String[]
because there's no guarantee that every item in the array is of the same type
(String in this example).