the key program: ArrayList al = new ArrayList(); al.add("1"); al.add("2"); al.add("3"); al.add("4"); //this is wrong,why?? String[] str = (String[]) al.toArray(); //but this is crrect. Object[] obj = al.toArray(); for (int i = 0; i < obj.length; i++) { String str = (String) obj[i]; }
The toArray() method returns an Object[]. It may contain Strings inside, but the array itself is fundamentally an Object[] not a String[], and cannot ever be cast to String[]. (String[] is a type of Object[]; and Object[] is not a type of String[].) If you want to create a String[] array (or other array type more specific than Object[]) then you must use toArray(Object[]) rather than toArray(). This allows you to create a specific type of array beforehand, and then load it in one step:
or alternately:
The second option is a bit strange - if you create an array which is the right type but too small for the size of your collection, toArray(Object[]) will merely use the type of the array provided in the argument, and will create a new array of the same type but different size. I prefer the first method as it seems more straightforward (and doesn't create an extra object which is discarded) -but either way works. [ November 05, 2002: Message edited by: Jim Yingst ]