我已经实现了一个从数组列表中删除元素的函数。我不应该是ArrayList库!请参阅下面的代码:
/**
* removes a LendItem at a specified (index) position.
* This functions returns the item removed from the list or null if no such item exists. This
* function leaves no gaps, that means all items after the removed item are shifted one position.
* @param list is the item to be removed
* @param n is the index of the item to be removed
* @return the removed item
*/
public static LendItem remove(LendItemArrayList list, int n) {
if (list.next == 0) {
return null;
}
if (n < 0 || n > list.INITIAL_SIZE) {
return null;
}
LendItem itemToBeRemoved = list.lendItems[n]; // itemToBeRemoved is the item which has the index n, which we want to remove from the list.
int i;
for (i = n; i < list.next - 1; i++) { // iterate through the list, starting where the index of the itemToBeRemoved is.
list.lendItems[i] = list.lendItems[i + 1];
}
list.lendItems[i] = null;
list.next--;
return itemToBeRemoved;
}
这是班级:
public class LendItemArrayList {
int INITIAL_SIZE = 20;
boolean resizeable = false;
LendItem[] lendItems = new LendItem[INITIAL_SIZE];
int next = 0;
}
我已经使用已经提供的一些测试方法测试了我的函数,并且我只是失败了其中一个。具体来说,测试称为:
removeNonExistingElement
它会像这样失败:
java.lang.AssertionError:添加了10个元素,接下来应该是10个(没有变化)但是找到了9个。
修改 添加了add()函数。
public static boolean add(LendItemArrayList list, LendItem p) {
if (list.next == list.lendItems.length) {
if (list.resizeable == false) {
return false;
}
}
if (list.next == list.lendItems.length) {
if (list.resizeable == true) {
LendItem[] resizedList = new LendItem[list.lendItems.length*2];
for (int i = 0; i < list.next; i++) {
resizedList[i] = list.lendItems[i];
}
list.lendItems = resizedList;
}
}
list.lendItems[list.next++] = p;
return true;
}
答案 0 :(得分:1)
保持原样,因为它会检查指数是否超出范围。
if (n < 0 || n >= list.INITIAL_SIZE) {
return null;
}
接下来,添加以下代码:
if (list.lendItems[n] == null) {
return null;
}
之后,您可能会或可能不会添加if语句来检查给定列表是否为空。除非需要使用它,否则没有区别。
if (list.next == 0){
return null;
}
答案 1 :(得分:0)
更改此行:
if (n < 0 || n > list.INITIAL_SIZE) {
对此:
if (n < 0 || n >= list.INITIAL_SIZE) {
>=
意味着更大或更平等。如果n == list.INITIAL_SIZE
,那么该项也不会被移除,因为索引从0开始,列表中的最后一个值的索引大小为1.它是其中一个开始编程时会伤害你的大脑。