我使用以下代码将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];

正确的做法是什么?


当前回答

对于你的想法,实际上你正在接近成功,但如果你这样做应该没问题:

for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];

顺便说一句,使用Arrays实用程序方法是非常好的,使代码优雅。

其他回答

我看到已经提供了一些解决方案,但没有任何原因,所以我会详细解释这一点,因为我相信,知道你做错了什么,只是为了从给定的回复中获得“一些东西”,这是同样重要的。

首先,让我们看看甲骨文公司会怎么说

 * <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]);

希望这足够清楚。

System.arraycopy的另一个替代方案:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

谷歌集合框架提供了一个很好的转换方法,因此您可以将对象转换为字符串。唯一的缺点是它必须从Iterable到Iterable,但这是我要做的方式:

Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
        String apply(Object from){
             return from.toString();
        }
 });

这样你就不用数组了,但我认为这是我更喜欢的方式。

在Java 8中:

String[] strings = Arrays.stream(objects).toArray(String[]::new);

转换其他类型的数组:

String[] strings = Arrays.stream(obj).map(Object::toString).
                   toArray(String[]::new);

对于你的想法,实际上你正在接近成功,但如果你这样做应该没问题:

for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];

顺便说一句,使用Arrays实用程序方法是非常好的,使代码优雅。