所以我在理解从arraylist中删除节点到底发生了什么有点麻烦。我的老师给全班同学讲了它的作用,但我正试图通过它来理解它。
public Object remove(int index)
{
//checking bounds
if(index < 0 || index >= size)
throw new IndexOutOfBoundsException("Invalid index " + index);
Object removedData = array[index]; //save removed
//shift array to the left
for (int i = index+1; i < size; i++)
array[i-1] = array[i];
//So this for loop is supposed to go to the node after the one we are
//trying to remove, then make the pointer from the previous point to it?
//decrement size and return removed data
size = size-1;
return removedData;
}
现在举一个具体的例子,在评论表上他有一个问题要删除第二个节点。
那么我还会使用索引吗? 我把它写成这样的东西:
public Object remove(int index)
{
//checking bounds
if(index < 0 || index >= size)
throw new IndexOutOfBoundsException("Invalid index " + index);
Object removedData = array[index]; //save removed
//shift array to the left
for (int i = index3; i < size; i++)
array[2] = array[3];
//Here is where I changed the numbers to be specifically for the 2nd
// node, but I'm not sure if this is right.
//decrement size and return removed data
size = size-1;
return removedData;
}
答案 0 :(得分:-1)
您需要做的就是将index
硬编码为1
(因为数组从零开始,第一个索引为0,第二个为1)。
public Object removeSecond()
{
int index = 1;
// all the same code as the original method
}