Problem when copying array of different types using Arrays.copyOf
- by Shervin
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?