[Java] ArrayList <String> is converted to a String array.
The toArray () method in Java's Collections class can convert dynamic arrays such as ArrayList <String>, static arrays with an indefinite length, and fixed-length arrays String []
However, the following conversion method is incorrect.
String[] strArray = (String[]) arrayList.toArray();
If you execute this operation, the following errors will occur:
Exception in thread "xx" java. lang. ClassCastException: [Ljava. lang. Object; cannot be cast to [Ljava. lang. String;
For example:
The correct method should be written as follows:
String[] strArrayTrue = (String[]) arrayList.toArray(new String[0]);
For example, the following program is normal:
Import java. util. *; public class ArrayListToStrArr {public static void main (String [] args) {ArrayList <String> arrayList = new ArrayList <String> (); arrayList. add ("1"); arrayList. add ("2"); // The Correct Conversion Method String [] strArrayTrue = (String []) arrayList. toArray (new String [0]); for (String str: strArrayTrue) {System. out. println (str);} // incorrect conversion method // String [] strArray = (String []) arrayList. toArray ();}}Similarly, it is promoted to the array ArrayList <Integer> and so on.