问题
我使用以下代码将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;
但这会导致运行时错误:Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
这样做的正确方法是什么?
#1 热门回答(342 赞)
System.arraycopy
的另一种替代方案:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
#2 热门回答(55 赞)
System.arraycopy可能是最有效的方式,但对于美学,我更喜欢:
Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
#3 热门回答(49 赞)
我看到已经提供了一些解决方案,但没有任何原因,所以我将详细解释这一点,因为我认为知道你做错了什么同样重要,只是为了从给定的回复中得到"某些东西"。
首先,让我们看看Oracle有什么话要说
* <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.
它可能看起来不重要但是你会看到它......那么下面的行怎么会失败呢?列表中的所有对象都是String但它不会转换它们,为什么?
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]);
希望它足够清楚。