简体   繁体   English

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

[英]How to convert object array to string array in Java

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; 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 ? 这样做的正确方法是什么?

System.arraycopy另一种替代方法:

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

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

System.arraycopy可能是最有效的方式,但对于美学,我更喜欢:

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

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! javadoc说的是! It will instatiate a new array, what it will be of Objects!!! 它将实现一个新的数组,它将是什么对象!

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. 希望它足够清楚。

The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. google集合框架提供了一个很好的转换方法,因此您可以将对象转换为字符串。 The only downside is that it has to be from Iterable to Iterable but this is the way I would do it: 唯一的缺点是它必须是从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();
        }
 });

This take you away from using arrays,but I think this would be my prefered way. 这会让你远离使用数组,但我认为这将是我的首选方式。

If you want to get a String representation of the objects in your array, then yes, there is no other way to do it. 如果你想获得数组中对象的String表示,那么是的,没有其他方法可以做到这一点。

If you know your Object array contains Strings only, you may also do (instread of calling toString()): 如果你知道你的Object数组只包含字符串,你也可以这样做(调用toString()的instread:)

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[] , eg this would work: 唯一可以使用强制转换为Object_Array的String []的情况是它引用的数组实际上是否定义为String [],例如这可以工作:

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

This one is nice, but doesn't work as mmyers noticed, because of the square brackets: 这个很好,但是因为方括号而不像mmyers注意到的那样:

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

This one is ugly but works: 这个很丑,但有效:

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

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实用程序方法非常好,使代码更优雅。

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

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

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

Easily change without any headche Convert any object array to string array Object drivex[] = {1,2}; 无任何头部轻松更改将任何对象数组转换为字符串数组对象drivex [] = {1,2};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM