mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
!874 修复ArrayUtil.insert()不支持原始类型数组的问题
Merge pull request !874 from emptypoint/fix-ArrayUtil-insert
This commit is contained in:
commit
8ae9387336
@ -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);
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user