我使用以下代码将Object数组转换为String数组:
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();
但我想知道是否有另一种方法来做到这一点,比如:
String_Array=(String[])Object_Array;
但是这会导致一个运行时错误:线程"AWT-EventQueue-0"中的异常不能强制转换为[Ljava.lang.String];
正确的做法是什么?
我看到已经提供了一些解决方案,但没有任何原因,所以我会详细解释这一点,因为我相信,知道你做错了什么,只是为了从给定的回复中获得“一些东西”,这是同样重要的。
首先,让我们看看甲骨文公司会怎么说
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
它可能看起来不重要,但正如你所看到的……那么下面这行失败了什么呢?列表中的所有对象都是字符串,但它不转换它们,为什么?
List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
可能,许多人会认为这段代码也在做同样的事情,但事实并非如此。
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
实际上,编写的代码是这样做的。javadoc在说!它将实例化一个新的数组,它将是什么对象!!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
所以tList。toArray实例化的是对象而不是字符串…
因此,本文中没有提到的自然解决方案,但它是Oracle推荐的解决方案
String tArray[] = tList.toArray(new String[0]);
希望这足够清楚。
这个很好,但不像mmyers注意到的那样,因为方括号:
Arrays.toString(objectArray).split(“,”)
下面这个很丑,但很管用:
Arrays toString (objectArray)。replaceFirst ("^\\[", "").replaceFirst ("\\]$", ""). (“分裂,”)
如果使用此代码,必须确保对象的toString()返回的字符串不包含逗号。
如果您想获得数组中对象的String表示形式,那么是的,没有其他方法可以做到这一点。
如果你知道你的对象数组只包含字符串,你也可以这样做(而不是调用toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
你可以使用Object_Array的String[]类型转换的唯一情况是,如果它引用的数组实际上被定义为String[],例如,这将工作:
Object[] o = new String[10];
String[] s = (String[]) o;