Java, toArray () method

Error codes:

 1     private void ArraytoList() {
 2         // Array--->List
 3         String[] strArray = new String[] { "aa", "bb" };
 4         List<String> list = new ArrayList<String>(Arrays.asList(strArray));
 5         list.add("cc");
 6         // List--->Array
 7         String[] strArray2;
 8         try {
 9             strArray2 = (String[]) list.toArray();
10         } catch (Exception e) {
11             Log.i("ToArray", "failure:" + e.getMessage());
12         }
13     }

 

Causes of List.toArray () returns the type Object, cast occurs when ClassCastException

Modify the code:

 1     private void ArraytoList() 
 2         // Array--->List
 3         String[] strArray = new String[] { "aa", "bb" };
 4         List<String> list = new ArrayList<String>(Arrays.asList(strArray));
 5         list.add("cc");
 6         // List--->Array
 7         String[] strArray2 = null;
 8         try {
 9             strArray2 = list.toArray(new String[0]);
10         } catch (Exception e) {
11             Log.i("ToArray", "failure:" + e.getMessage());
12         }
13         for (String element : strArray2) {
14             Log.i("ToArray", "strArray2:" + element);
15         }
16     }

 

The following two pieces of code consistent results:

1 strArray2 = list.toArray(new String[0]);

2 strArray2 = new String[list.size()]; 3 strArray2 = list.toArray(strArray2);

 

toArray method with no parameters, an array of Object structure, and then to copy data, at this time will generate a ClassCastException transformation, and toArray method with parameters, is based on the type of a parameter array, a configuration of a corresponding type, consistent with the size empty array length ArrayList, although the method itself or returns the result as an array of Object, but because ComponentType ComponentType structure consistent with the need to use an array of transition, the transition will not produce abnormal.

ToArray later use can refer to the following ways:

1 1. Long[] l = new Long[<total size>];
2    list.toArray(l);
3 4 2. Long[] l = (Long[]) list.toArray(new Long[0]);
5 6 3. Long[] a = new Long[<total size>];
7    Long[] l = (Long[]) list.toArray(a);

 

Guess you like

Origin www.cnblogs.com/chaoaishow/p/11611526.html