Java中如何将对象数组转换为字符串数组 [英] How to convert object array to string array in Java
本文介绍了Java中如何将对象数组转换为字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码将对象数组转换为字符串数组:
I use the following code to convert an Object array to a String array :
Object Object_Array[]=new Object[100];
// ... get values in the Object_Array
String String_Array[]=new String[Object_Array.length];
for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();
但是我想知道是否有另一种方法可以做到这一点,例如:
But I wonder if there is another way to do this, something like :
String_Array=(String[])Object_Array;
但这会导致运行时错误:Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object;不能强制转换为 [Ljava.lang.String;
But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
正确的做法是什么?
推荐答案
System.arraycopy
的另一种替代方案:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
这篇关于Java中如何将对象数组转换为字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文