如何将对象数组转换成Java中的字符串数组?

时间:2021-05-03 22:28:35

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;

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;

但是这会导致运行时错误:线程“AWT-EventQueue-0”java.lang的异常。ClassCastException:[Ljava.lang.Object;不能转换为[Ljava.lang.String;

What's the correct way to do it ?

正确的方法是什么?

11 个解决方案

#1


335  

Another alternative to System.arraycopy:

另一个替代System.arraycopy:

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

#2


53  

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

系统。arraycopy可能是最有效的方法,但对于美学,我更喜欢:

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

#3


48  

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?

它看起来并不重要,但你会发现它是……那么下面这一行失败了什么呢?列表中的所有对象都是字符串,但它不会转换它们,为什么?

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.

希望很清楚。

#4


41  

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

#5


7  

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,但这是我的方法:

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.

这让你远离了使用数组,但我认为这是我喜欢的方式。

#6


5  

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:

当您可以使用cast到Object_Array的字符串时,唯一的情况是如果它引用的数组实际上被定义为String[],例如:

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

#7


4  

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()返回的字符串不包含逗号。

#8


2  

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.

顺便说一下,使用数组实用程序的方法非常好,使代码更加优雅。

#9


1  

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

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

#10


1  

You can use type-converter. To convert an array of any types to array of strings you can register your own converter:

您可以使用类型转换程序。要将任何类型的数组转换为字符串数组,您可以注册自己的转换器:

 TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {

        @Override
        public String[] convert(Object[] source) {
            String[] strings = new String[source.length];
            for(int i = 0; i < source.length ; i++) {
                strings[i] = source[i].toString();
            }
            return strings;
        }
    });

and use it

并使用它

   Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
   String[] strings = TypeConverter.convert(objects, String[].class);

#11


0  

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

不需要任何headche将任何对象数组转换为string数组对象drivex[] = {1,2};

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

#1


335  

Another alternative to System.arraycopy:

另一个替代System.arraycopy:

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

#2


53  

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

系统。arraycopy可能是最有效的方法,但对于美学,我更喜欢:

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

#3


48  

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?

它看起来并不重要,但你会发现它是……那么下面这一行失败了什么呢?列表中的所有对象都是字符串,但它不会转换它们,为什么?

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.

希望很清楚。

#4


41  

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

#5


7  

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,但这是我的方法:

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.

这让你远离了使用数组,但我认为这是我喜欢的方式。

#6


5  

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:

当您可以使用cast到Object_Array的字符串时,唯一的情况是如果它引用的数组实际上被定义为String[],例如:

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

#7


4  

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()返回的字符串不包含逗号。

#8


2  

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.

顺便说一下,使用数组实用程序的方法非常好,使代码更加优雅。

#9


1  

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

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

#10


1  

You can use type-converter. To convert an array of any types to array of strings you can register your own converter:

您可以使用类型转换程序。要将任何类型的数组转换为字符串数组,您可以注册自己的转换器:

 TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {

        @Override
        public String[] convert(Object[] source) {
            String[] strings = new String[source.length];
            for(int i = 0; i < source.length ; i++) {
                strings[i] = source[i].toString();
            }
            return strings;
        }
    });

and use it

并使用它

   Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
   String[] strings = TypeConverter.convert(objects, String[].class);

#11


0  

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

不需要任何headche将任何对象数组转换为string数组对象drivex[] = {1,2};

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