这段代码是别人帮我写的
public void add(int index, E element)
if (index < 0 || index >= mList.length){
throw new IndexOutOfBoundsException(); // check if index is ok.
}
Object[] temp = new Object[mList.length + 1]; // create the new array into temp.
for (int i = 0, j = 0; j < temp.length; ++i, ++j){ // loop into the array by comparing the first array to the second array's index i&j
if ( i == index ) { // check if i is valid
temp[index] = element; // insert element into the array
--i; // decrement original array to cancel out j temp array
} else {
temp[j] = mList[i]; //
}
}
mList = temp;
}
现在我需要
public E remove(int index)
我需要再次创建一个临时数组吗?
我知道有两个数组,我只是在当前数组上做一个for循环,这是temp吗?
如果你想用类似于add的方式来做,那么是的,你需要一个临时数组。
public E remove(int index) {
Object[] temp = new Object[mList.length + 1];
for (int i = 0; j < mList.length; ++i) {
if(i<index) temp[i]=mList[i];
if(i>index) temp[i-1]=mList[i];
//N.B. not added if i == index
}
mList = temp;
}
总而言之,你没有从数组中删除元素,只是没有将其添加到新数组中。
如果你想要一个更好的解决方案,你应该看看System.arraycopy()
和Arrays.copyOf()
。试一试,如果你有困难,不要羞于开口。
如果你没有强制使用数组,我建议你使用集合。例如,List就可以很好地满足您的需求。