Java的容器类Collections中toArray()方法,可以把诸如ArrayList<String>的动态数组、不定长转化静态数组、定长数组String[]
但是,如下的转化方式是错误的。
String[] strArray = (String[]) arrayList.toArray();
如果这样执行会导致如下的错误:
Exception in thread "xx" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
如下图:
正确的方式应该写成:
String[] strArrayTrue = (String[]) arrayList.toArray(new String[0]);
比如,如下的一段程序,是正常的:
import java.util.*; public class ArrayListToStrArr { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("1"); arrayList.add("2"); // 正确转化方式 String[] strArrayTrue = (String[]) arrayList.toArray(new String[0]); for (String str : strArrayTrue) { System.out.println(str); } // 错误的转化方式 // String[] strArray = (String[]) arrayList.toArray(); } }
同理推广到数组ArrayList<Integer>等
时间: 2024-08-27 02:11:19