List转数组:java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

List.toArray() forced type conversion error: 

List<String> list= new ArrayList<String>();
//根据小区id查询人行闸机
List<ResourceShadow> shadowList = queryAreaEntranceBrakesByPlace(dgpData.getProjectid(), communityid);
if(shadowList != null && shadowList.size() >0){
	for (ResourceShadow resourceShadow : shadowList) {
		list.add(resourceShadow.getResid());
	}
}
//人行闸机id
String[] brakeIdArr = (String[]) list.toArray();

 The reason is: Object[] cannot be converted to String[]. The only way to convert is to take out each element and then convert it.

The coercive type conversion in java is only for a single object. It is impossible to lazily convert the entire array into another type of array.

Object[] arr = list.toArray();
for (int i = 0; i < arr.length; i++) {
	String e = (String) arr[i];
	System.out.println(e);
}

ArrayList provides a very convenient method toArray to convert List to array. toArray has two overloaded methods:

1.list.toArray();

2.list.toArray(T[]  a);

For the first overloaded method, the list is directly converted to an Object[] array;

The second method is to convert the list into an array of the type you need. Of course, when we use it, it will be converted to the same type as the content of the list.

It is more convenient to change to the following:

//参数指定空数组,节省空间

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

还可以这样写:

String[] y = x.toArray(new String[x.size()]);

new String[0] is just to specify the shape parameters of the function, the length of the final String[] is determined by the length of your list storage content 

list.toArray(new String[0]);//转化成String数组

list.toArray(new int[0]);   //转化成int数组

https://blog.csdn.net/tomcat_2014/article/details/51164080

https://www.cnblogs.com/zzzzw/p/5171221.html

https://www.cnblogs.com/goloving/p/7693388.html

https://blog.csdn.net/defineshan/article/details/52763637?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.control

https://blog.csdn.net/jjdhshdahhdd/article/details/8290555?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control

Guess you like

Origin blog.csdn.net/ZHOU_VIP/article/details/110875603