Java.util.List.toArray () experience in usingTags: objectstringexceptionlistnull 2012-02-28 11:23 18713 people read Comments (0) Favorites Report Category: Android_ character processing (2)
Copyright NOTICE: This article is the original article of the blogger, without the permission of the blogger may not be reproduced.
After the following code executes:
[Java] View plain copy Private void onbuttonlisttoarrayclick () { // array--->List string[] strarray = new String[] { "AA", "BB" }; List<String> List = new arraylist<string> (Arrays.aslist (strarray)); list.add ("CC"); // list--->Array String[] strArray2; try { strArray2 = (string[]) list.toarray (); } catch (exception e) { &NBSP;&NBSP;LOG.I ("ToArray", "Failure:" + e.getmessage ()); } }
Exception occurred
Because List.toarray () returns the object type, it occurs when the cast is classcastexception
The procedure is amended as follows:
[Java] View plain copy Private void onbuttonlisttoarrayclick () { // array--->List string[] strarray = new String[] { "AA", "BB" }; List<String> List = new arraylist<string> (Arrays.aslist (strarray)); list.add ("CC"); // list--->Array String[] strArray2 = null; try { strarray2 = list.toarray (new String[0]); } catch (exception e) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.I ("ToArray", "Failure:" + e.getmessage ()); } for (string element : strarray2) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.I ("ToArray", "StrArray2:" + element); } }
Run Result:
The method above
[Java] view plain Copy strArray2 = List.toarray (new string[0));
As with the following method
[Java] view plain copy strArray2 = new String[list.size ()];