LANG-567 - ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed types very well

Also remove unnecessary main() and suite() from test class

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@892114 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Sebastian Bazley 2009-12-18 02:50:21 +00:00
parent eb2b517b46
commit 2f8f67ab29
2 changed files with 24 additions and 13 deletions

View File

@ -2956,10 +2956,19 @@ public class ArrayUtils {
} else if (array2 == null) {
return clone(array1);
}
T[] joinedArray = (T[]) Array.newInstance(array1.getClass().getComponentType(),
array1.length + array2.length);
final Class<?> type1 = array1.getClass().getComponentType();
T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
try {
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
} catch (ArrayStoreException ase) {
// Check if problem is incompatible types
final Class<?> type2 = array2.getClass().getComponentType();
if (!type1.isAssignableFrom(type2)){
throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName());
}
throw ase; // No, so rethrow original
}
return joinedArray;
}

View File

@ -19,10 +19,7 @@ package org.apache.commons.lang3;
import java.util.Arrays;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Tests ArrayUtils add methods.
@ -31,14 +28,19 @@ import junit.textui.TestRunner;
* @version $Id$
*/
public class ArrayUtilsAddTest extends TestCase {
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(ArrayUtilsAddTest.class);
suite.setName("ArrayUtils add Tests");
return suite;
public void testJira567(){
Number[] n;
// Valid array construction
n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
assertEquals(2,n.length);
assertEquals(Number.class,n.getClass().getComponentType());
try {
// Invalid - can't store Long in Integer array
n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
fail("Should have generated IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
public void testAddObjectArrayBoolean() {