我有一个输入数组 [3, 5, 12, 8],我想要一个输出数组(输入不能被改变),与输入数组相同,但是在5和12之间插入元素7,插入到输入数组的索引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。
add.getClass().newInstance()
应该可以工作。 - EpicPandaForceout.set(newIndex, add)
无法工作,因为new ArrayList<>(newIndex + 1)
分配了一个具有newIndex + 1
元素空间的ArrayList
,但它是空的;你不能随意在中间设置索引。你必须先用newIndex
元素填充ArrayList
;你不能为大于当前大小的索引set
元素。 - Louis Wasserman