!874 修复ArrayUtil.insert()不支持原始类型数组的问题

Merge pull request !874 from emptypoint/fix-ArrayUtil-insert
This commit is contained in:
Looly 2022-11-24 04:46:15 +00:00 committed by Gitee
commit 8ae9387336
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 30 additions and 2 deletions

View File

@ -477,9 +477,16 @@ public class ArrayUtil extends PrimitiveArrayUtil {
index = (index % len) + len;
}
final Object result = Array.newInstance(array.getClass().getComponentType(), Math.max(len, index) + newElements.length);
// 已有数组的元素类型
Class<?> originComponentType = array.getClass().getComponentType();
Object newEleArr = newElements;
// 如果 已有数组的元素类型是 原始类型则需要转换 新元素数组 为该类型避免ArrayStoreException
if (originComponentType.isPrimitive()) {
newEleArr = Convert.convert(array.getClass(), newElements);
}
final Object result = Array.newInstance(originComponentType, Math.max(len, index) + newElements.length);
System.arraycopy(array, 0, result, 0, Math.min(len, index));
System.arraycopy(newElements, 0, result, index, newElements.length);
System.arraycopy(newEleArr, 0, result, index, newElements.length);
if (index < len) {
System.arraycopy(array, index, result, index + newElements.length, len - index);
}

View File

@ -577,4 +577,25 @@ public class ArrayUtilTest {
a = null;
Assert.assertTrue(ArrayUtil.isAllNull(a));
}
@Test
public void testInsertPrimitive() {
final boolean[] booleans = new boolean[10];
final byte[] bytes = new byte[10];
final char[] chars = new char[10];
final short[] shorts = new short[10];
final int[] ints = new int[10];
final long[] longs = new long[10];
final float[] floats = new float[10];
final double[] doubles = new double[10];
boolean[] insert1 = ArrayUtil.insert(booleans, 0, 0, 1, 2);
byte[] insert2 = ArrayUtil.insert(bytes, 0, 1, 2, 3);
char[] insert3 = ArrayUtil.insert(chars, 0, 1, 2, 3);
short[] insert4 = ArrayUtil.insert(shorts, 0, 1, 2, 3);
int[] insert5 = ArrayUtil.insert(ints, 0, 1, 2, 3);
long[] insert6 = ArrayUtil.insert(longs, 0, 1, 2, 3);
float[] insert7 = ArrayUtil.insert(floats, 0, 1, 2, 3);
double[] insert8 = ArrayUtil.insert(doubles, 0, 1, 2, 3);
}
}