What is happening is that stock_list.toArray()
is creating an Object[]
rather than a String[]
and hence the typecast is failing.
The correct code would be:
String [] stockArr = stockList.toArray(new String[stockList.size()]);
or even
String [] stockArr = stockList.toArray(new String[0]);
For more details, refer to the javadocs for the two overloads of List.toArray
.
(From a technical perspective, the reason for this API behaviour / design is that an implementation of the List<T>.toArray()
method has no information of what the <T>
is at runtime. All it knows is that the raw element type is Object
. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplies array is big enough, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)
String [] stockArr = (String[]) stock_list.toArray(new String[0]);
refer java doc here – Nishant Mar 21 '11 at 6:11