-1
그래서 나는 arraylist에서 노드를 제거하는 것과 정확히 무슨 일이 벌어지고 있는지 이해하는 데 어려움을 겪고 있습니다. 저의 선생님은 수업 내용에 일반적인 유인물을주었습니다. 그러나 이해하기 위해 그것을 배우려고합니다.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;
}
답장을 보내 주셔서 감사합니다. for 루프가 작동하는 방식에 대해 좀 더 설명해 주시겠습니까? – cinnstix
메소드에 나타날 때마다'index'를 1로 대체하십시오. 그게 다야. 'for' 루프의 본문을 바꾸는 것은 잘못된 것입니다. 왜냐하면 목록의 크기를 줄이기 전에, * 모든 * 후속 요소를 하나씩 옮겨서 비워 둔 위치를 채워야하기 때문입니다. – gknicker
감사합니다. 당신은 그것에 대해 무례하지 않아도됩니다. – cinnstix