我有一个输入数组 [3, 5, 12, 8] 并且我想要一个与输入相同的输出数组(输入不能受到影响),但元素 7 插入在 5 和 12 之间,所以在索引处输入数组的 2。
这是我目前所拥有的。我注释掉了无法编译的代码,并添加了一些在尝试这种或那种方式时出现的问题:
public static <O>ArrayList<O> addToSet(O[] in,O add,int newIndex){
// O obj = (O) new Object(); //this doesnt work
// ParameterizedType obj = (ParameterizedType) getClass().getGenericSuperClass(); // this is not even recognized
ArrayList<O> out = multipleOfSameSet(obj, in.length);
if (newIndex > in.length){
out = new ArrayList<>(newIndex+1); // also noticed that initializing an ArrayList
//like this throws an IndexOutOfBoundsException when i try to run out.get(),
// could someone explain why??
out.set(newIndex, add);
}
int j = 0;
int i = 0;
while(j<in.length+1){
if (j==newIndex){
out.set(j, add);
} else if(i<in.length){
out.set(j, in[i]);
i++;
}
j++;
}
return out;
}
数组组件类型可以是 String、Integer 甚至是 JPanel。
最佳答案
这是代码的通用版本
@SuppressWarnings("unchecked")
public <T> T[] insertInCopy(T[] src, T obj, int i) throws Exception {
T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length + 1);
System.arraycopy(src, 0, dst, 0, i);
dst[i] = obj;
System.arraycopy(src, i, dst, i + 1, src.length - i);
return dst;
}
但您可能希望专门处理原始类型的方法。我的意思是,泛型和数组不能很好地混合——所以你会遇到 int 的问题,需要使用包装器类型:
@Test
public void testInsertInTheMiddle() throws Exception {
Integer[] in = {3, 5, 12, 8};
Integer[] out = target.insertInCopy(in, 7, 2);
assertEquals(out, new Integer[] {3, 5, 7, 12, 8});
}
关于java - 如何编写通用方法在数组中插入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31599313/