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

时间:2009-06-19 16:00:04

标签: java arrays string

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

这样做的正确方法是什么?

11 个答案:

答案 0 :(得分:360)

System.arraycopy的另一种选择:

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

答案 1 :(得分:57)

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

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

答案 2 :(得分:57)

在Java 8中:

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

转换其他类型的数组:

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

答案 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实例化一个Objects而不是字符串......

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

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

希望它足够清楚。

答案 4 :(得分:7)

google collections框架提供了一个很好的转换方法,因此您可以将对象转换为字符串。唯一的缺点是必须从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();
        }
 });

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

答案 5 :(得分:5)

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

如果你知道你的Object数组只包含字符串,你也可以这样做(调用toString()的实例):

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

唯一可以使用强制转换为Object_Array的String []的情况是它引用的数组实际上是否定义为String [],例如这会奏效:

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

答案 6 :(得分:5)

这个很好,但是由于方括号:

,因为mmyers没注意到

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

这个很丑,但有效:

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

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

答案 7 :(得分:2)

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

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

BTW,使用Arrays实用程序方法非常好,使代码更优雅。

答案 8 :(得分:1)

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

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

答案 9 :(得分:1)

您可以使用type-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;
        }
    });

并使用它

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

答案 10 :(得分:0)

轻松改变,没有任何头痛 将对象数组转换为字符串数组Object drivex [] = {1,2};

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