내 자신의 이중 연결 목록을 만들어야합니다. 나는 초보자이기 때문에 내 지식 부족을 용서해주십시오. 이 목록은 List java 인터페이스를 구현해야하므로 remove (int), remove (Object) 및 clear() 메서드도 있으며 clear() 메서드는 작업을 수행하지 않습니다. 목록의 모든 요소를 제거하고 일부만 제거하십시오. 여기 연결된 목록 .clear() 메서드가 제대로 작동하지 않습니다.
맑은() 방법 :public void clear() {
for (T t : this) {
this.remove(t);
}
this.remove(this.size);
}
제거 (Object) 메소드 :
public boolean remove(Object o) {
if (this.indexOf(o) >= 0){
remove(this.indexOf(o));
return true;
}
return false;
}
그리고 마지막으로, 제거 (int) 메소드 :
public T remove(int index) {
if (getNode(index) == null || this.isEmpty()) {
return null;
} else if (this.size == 1){
this.size = 0;
Node<T> currentNode = this.firstNode;
this.firstNode = null;
this.lastNode = null;
return currentNode.data;
}
Node<T> currentNode = this.getNode(index);
if (currentNode.nextNode != null){
if (currentNode.previousNode != null){
currentNode.previousNode.nextNode = currentNode.nextNode;
} else {
this.firstNode = currentNode.nextNode;
this.firstNode.previousNode = null;
this.size--;
return currentNode.data;
}
}
if (currentNode.previousNode != null){
if (currentNode.nextNode != null) {
currentNode.nextNode.previousNode = currentNode.previousNode;
} else {
this.lastNode = currentNode.previousNode;
this.lastNode.nextNode = null;
this.size--;
return currentNode.data;
}
}
currentNode = currentNode.nextNode;
this.size--;
for(int i = index; i < this.size-1; i++){
currentNode = currentNode.nextNode;
currentNode.index--;
}
return currentNode.data;
}
가능한 경우 버그의 위치를 지적 할뿐만 아니라이 코드를 개선하는 데 도움을주십시오. 노력해 주셔서 감사합니다!
'for (T t : this) { this.remove (t); }'는 열거자를 완전히 망치고 있습니다. @ njzk2가 언급 된대로 – njzk2
대신에 for (int i = size() - 1; i> = 0; i--) {}'루프를 사용하면리스트를 반복하는 동안 코드가'ConcurrentModificationException'을 throw합니다. 당신이 항목을 제거하고 있습니다 – Branky
@ njzk2 감사합니다. 비록 더 이상 문제가 보이더라도 이것을 포함한 답을 만드십시오. –