从数组列表中删除节点(一般和特定)
Remove Node from Arraylist (General and Specific)
所以我在理解从数组列表中删除节点时究竟发生了什么时遇到了一些麻烦。我的老师给了 class 一份通用的讲义,说明它的作用,但我正在努力通过它来理解它。
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;
}
现在举个具体的例子,在评论中sheet他有一个问题要删除第二个节点。
那我还要用索引吗?
我把它写成这样:
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;
}
您所要做的就是将 index
硬编码为 1
(因为数组是从零开始的,第一个索引是 0,第二个是 1)。
public Object removeSecond()
{
int index = 1;
// all the same code as the original method
}
所以我在理解从数组列表中删除节点时究竟发生了什么时遇到了一些麻烦。我的老师给了 class 一份通用的讲义,说明它的作用,但我正在努力通过它来理解它。
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;
}
现在举个具体的例子,在评论中sheet他有一个问题要删除第二个节点。
那我还要用索引吗? 我把它写成这样:
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;
}
您所要做的就是将 index
硬编码为 1
(因为数组是从零开始的,第一个索引是 0,第二个是 1)。
public Object removeSecond()
{
int index = 1;
// all the same code as the original method
}