用复制不同Arrays.copyOf类型的数组时的问题 [英] Problem when copying array of different types using Arrays.copyOf

查看:365
本文介绍了用复制不同Arrays.copyOf类型的数组时的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个pretty很多东西需要作为参数的方法,并返回一个连接字符串,再与一些分隔符的价值presentation。

 公共静态字符串getConcatenated(字符DELIM,对象...名称){
的String []字符串数组= Arrays.copyOf(姓名,names.length,字符串[]类。); //这里异常
返回getConcatenated(DELIM,字符串数组);
}

和实际的方法

 公共静态字符串getConcatenated(字符DELIM,串...名称){
如果(名称== NULL || names.length == 0)
    返回;StringBuilder的SB =新的StringBuilder();的for(int i = 0; I< names.length;我++){
    字符串n =名字[I]
    如果(N!= NULL){
        sb.append(n.trim());
        sb.append(DELIM);
    }
}//删除最后DELIM
返回sb.substring(0,sb.length() - 1)的ToString();
}

和我有以下的JUnit测试:

 最后String中的两个= RedpillLinproUtils.getConcatenated('',Shervin,阿斯卡里);
Assert.assertEquals(结果,Shervin阿斯卡里,二); //好最后弦乐3 = RedpillLinproUtils.getConcatenated(;,Shervin,阿斯卡里);
Assert.assertEquals(结果,Shervin;阿斯卡里,三); //好最后串的四个= RedpillLinproUtils.getConcatenated(;,Shervin,NULL,阿斯卡里,NULL);
Assert.assertEquals(结果,Shervin;阿斯卡里,四); //好最终弦五= RedpillLinproUtils.getConcatenated('/',1,2,空,3,4);
Assert.assertEquals(结果,1/2/3/4五); //失败

但是,测试在与异常的最后一部分失败

java.lang.ArrayStoreException
    在java.lang.System.arraycopy(本机方法)
    在java.util.Arrays.copyOf(Arrays.java:2763)

有人能找出错误?


解决方案

的原因

您不能在的String [] 把一个整数。这就是为什么你会得到 ArrayStoreException信息 Arrays.copyOf 则不进行转换。

从<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28U%5B%5D,%20int,%20java.lang.Class%29\"相对=nofollow>的API :


  

T [] copyOf(U []原创,诠释满足newLength,类&LT;扩展T []&GT; NEWTYPE)


  
  

抛出 ArrayStoreException信息 - 如果一个元素从复制原创是一个不可存储类的数组运行时类型 NEWTYPE


ArrayStoreException信息 API 有一个例子:


  

抛出,表明已尝试做出了错误类型的对象存储到一个对象数组。例如,下面的code生成一个 ArrayStoreException信息

 对象x [] =新的String [3];
    X [0] =新的整数(0);


另请参见


的修复

这是说,你其实并不需要一个字符串... Arrays.copyOf 的String [] 。你的 getConcatenated 可以只取对象... 键,它会工作得很好。

 公共静态字符串getConcatenated(字符DELIM,对象... OBJ文件){
    如果(OBJ文件== NULL || objs.length == 0)
        返回;    StringBuilder的SB =新的StringBuilder();
    对于(对象o:OBJ文件){
        如果(O!= NULL){
            如果(sb.length()&0)sb.append(DELIM);
            sb.append(o.toString()修剪());
        }
    }
    返回sb.toString();
}

现在你可以做到以下几点:

 的System.out.println(getConcatenated(;,Shervin,NULL,阿斯卡里,NULL));
    //输出Shervin;阿斯卡里    的System.out.println(getConcatenated(/,1,2,空,3,4));
    //输出1/2/3/4    的System.out.println(getConcatenated(:,,空,嘘,嘘));
    //输出嘘:嘘

请注意,这跟在原来的code,即修剪()并跳过空。

I am trying to create a method that pretty much takes anything as a parameter, and returns a concatenated string representation of the value with some delimiter.

public static String getConcatenated(char delim, Object ...names) {
String[] stringArray = Arrays.copyOf(names, names.length, String[].class); //Exception here
return getConcatenated(delim, stringArray);
}

And the actual method

public static String getConcatenated(char delim, String ... names) {
if(names == null || names.length == 0)
    return "";

StringBuilder sb = new StringBuilder();

for(int i = 0; i < names.length; i++) {
    String n = names[i];
    if(n != null) {
        sb.append(n.trim());
        sb.append(delim);
    }
}

//Remove the last delim
return sb.substring(0, sb.length()-1).toString();
}

And I have the following JUnit test:

final String two = RedpillLinproUtils.getConcatenated(' ', "Shervin", "Asgari");
Assert.assertEquals("Result", "Shervin Asgari", two); //OK

final String three = RedpillLinproUtils.getConcatenated(';', "Shervin", "Asgari");
Assert.assertEquals("Result", "Shervin;Asgari", three); //OK

final String four = RedpillLinproUtils.getConcatenated(';', "Shervin", null, "Asgari", null);
Assert.assertEquals("Result", "Shervin;Asgari", four); //OK

final String five = RedpillLinproUtils.getConcatenated('/', 1, 2, null, 3, 4);
Assert.assertEquals("Result", "1/2/3/4", five); //FAIL

However, the test fails on the last part with the exception:

java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOf(Arrays.java:2763)

Can someone spot the error?

解决方案

The cause

You can't put an Integer in a String[]. That's why you get ArrayStoreException. Arrays.copyOf does no conversion.

From the API:

T[] copyOf(U[] original, int newLength, Class< ? extends T[]> newType)

Throws: ArrayStoreException - if an element copied from original is not of a runtime type that can be stored in an array of class newType

The ArrayStoreException API has an example:

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:

    Object x[] = new String[3];
    x[0] = new Integer(0);

See also


The fix

That said, you actually don't need a String... and Arrays.copyOf to a String[]. Your getConcatenated can just take Object... and it'd work just fine.

public static String getConcatenated(char delim, Object... objs) {
    if(objs == null || objs.length == 0)
        return "";

    StringBuilder sb = new StringBuilder();
    for (Object o : objs) {
        if(o != null) {
            if (sb.length() > 0) sb.append(delim);
            sb.append(o.toString().trim());
        }
    }
    return sb.toString();
}

Now you can do the following:

    System.out.println(getConcatenated(';', "Shervin", null, "Asgari", null));
    // prints "Shervin;Asgari"

    System.out.println(getConcatenated('/', 1, 2, null, 3, 4));
    // prints "1/2/3/4"

    System.out.println(getConcatenated(':', "  ", null, "boo", "boo"));
    // prints "boo:boo"

Note that this follows the intended specification in the original code, i.e. trim() and skips null.

这篇关于用复制不同Arrays.copyOf类型的数组时的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆