[英]Java how to convert List<Object[]> into a String[]
I found a lot of ways to convert List< Object >
to String[]
but it did't work for List< Object[] >
.我找到了很多
convert List< Object >
为String[]
但它不适用于List< Object[] >
。 I'm getting error:我收到错误:
java.lang.RuntimeException: java.lang.ClassCastException:
[Ljava.lang.String; cannot be cast to java.lang.String
Code:代码:
public String[] listToArray(List<Object[]> inputList) {
String[] outputArray = new String[inputList.size()];
int index = 0;
for(Object obj : inputList) {
outputArray[index] = (String) obj;
index++;
}
return outputArray;
}
Here are the changes I have done to your code to overcome the class cast exception and other possible exceptions which may occur.以下是我对您的代码所做的更改,以克服可能发生的类转换异常和其他可能的异常。 Your list contains object[] and not Object.
您的列表包含 object[] 而不是 Object。 Hence the casting to String is throwing error.
因此,转换为 String 会引发错误。 You can avoid it by iterating it at 2 levels, one for every object[] in list and then every object in object[].
您可以通过在 2 个级别迭代它来避免它,一个用于列表中的每个对象 [],然后是对象 [] 中的每个对象。 As your List is of Object[] type your code to initialize String[] of list size is not correct under all circumstances, you may end up with Array index out of bounds exception, hence I am adding every string to list and then convert the list to array at last step.
由于您的 List 是 Object[] 类型,因此您初始化列表大小的 String[] 的代码在所有情况下都不正确,您最终可能会遇到 Array index out of bounds 异常,因此我将每个字符串添加到列表中,然后转换在最后一步列出到数组。
public static String[] listToArray(List<Object[]> inputList) {
List<String> outputList = new ArrayList<String>();
for(Object[] obj : inputList) {
for(Object obj1 : obj)
{
outputList.add((String) obj1);
}
}
return outputList.toArray(new String[outputList.size()]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.