ArrayList ClassCastException

When trying to typecast Object array to the Actual array type, a runtime ClassCastException is thrown.

ArrayList lst = new ArrayList();
lst.add("String 1");
lst.add("String 2");
lst.add("String 3");

String[] strArr = (String[])lst.toArray();


Solution for this is to use the toArray method with argument.

String[] strArr = new String[0];
strArr = (String[]) lst.toArray(strArr);

No comments: