如何在Java中将对象数组转换为字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1018750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:19:31  来源:igfitidea点击:

How to convert object array to string array in Java

javaarraysstring

提问by Frank

I use the following code to convert an Object array to a String array :

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

But I wonder if there is another way to do this, something like :

但我想知道是否有另一种方法可以做到这一点,例如:

String_Array=(String[])Object_Array;

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;

但这会导致运行时错误: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

What's the correct way to do it ?

正确的做法是什么?

采纳答案by waxwing

Another alternative to System.arraycopy:

另一种选择System.arraycopy

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

回答by Yishai

System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:

System.arraycopy 可能是最有效的方式,但为了美观,我更喜欢:

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);

回答by Richard

The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:

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

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();
        }
 });

This take you away from using arrays,but I think this would be my prefered way.

这使您远离使用数组,但我认为这将是我的首选方式。

回答by david a.

If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.

如果您想获得数组中对象的字符串表示,那么是的,没有其他方法可以做到。

If you know your Object array contains Strings only, you may also do (instread of calling toString()):

如果你知道你的对象数组只包含字符串,你也可以这样做(代替调用 toString()):

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

The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:

您可以使用 Object_Array 的 String[] 强制转换的唯一情况是,它引用的数组实际上被定义为 String[] ,例如,这将起作用:

    Object[] o = new String[10];
    String[] s = (String[]) o;

回答by Ilya Boyandin

This one is nice, but doesn't work as mmyers noticed, because of the square brackets:

这个很好,但不像 mmyers 注意到的那样工作,因为方括号:

Arrays.toString(objectArray).split(",")

Arrays.toString(objectArray).split(",")

This one is ugly but works:

这是丑陋的,但有效:

Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")

Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")

If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.

如果使用此代码,则必须确保对象的 toString() 返回的字符串不包含逗号。

回答by ttt

For your idea, actually you are approaching the success, but if you do like this should be fine:

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

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

BTW, using the Arrays utility method is quite good and make the code elegant.

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

回答by Capagris

I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.

我看到已经提供了一些解决方案,但没有提供任何原因,因此我将详细解释这一点,因为我相信了解您做错了什么与仅从给定的回复中获得“有用的东西”一样重要。

First, let's see what Oracle has to say

先来看看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.

It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?

它可能看起来并不重要,但正如您将看到的那样... 那么下面这行会失败吗?列表中的所有对象都是 String 但它不会转换它们,为什么?

List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();   

Probably, many of you would think that this code is doing the same, but it does not.

可能很多人会认为这段代码在做同样的事情,但事实并非如此。

Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;

When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!

实际上,编写的代码正在做这样的事情。javadoc 是这么说的!它将创建一个新数组,它是什么对象!!!

Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;   

So tList.toArray is instantiating a Objects and not Strings...

所以 tList.toArray 正在实例化一个对象而不是字符串......

Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following

因此,这个线程中没有提到但Oracle推荐的自然解决方案是以下

String tArray[] = tList.toArray(new String[0]);

Hope it is clear enough.

希望它足够清楚。

回答by Rahul Chhangani

Easily change without any headche Convert any object array to string array Object drivex[] = {1,2};

无需任何麻烦即可轻松更改 将任何对象数组转换为字符串数组 Object drivex[] = {1,2};

    for(int i=0; i<drive.length ; i++)
        {
            Str[i]= drivex[i].toString();
            System.out.println(Str[i]); 
        }

回答by Vitalii Fedorenko

In Java 8:

在 Java 8 中:

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

To convert an array of other types:

转换其他类型的数组:

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

回答by Amit Kumar Sagar

Object arr3[]=list1.toArray();
   String common[]=new String[arr3.length];

   for (int i=0;i<arr3.length;i++) 
   {
   common[i]=(String)arr3[i];
  }