>我有一个*,我正在尝试让我的删除方法来删除并返回特定的目标项目。我尝试了很多不同的方法试图让它工作,但它一直给我 NPE。
这是我的第一个删除():
这是我的第二个 remove(),它能够使代码编译:
这是我的线性节点:
学生班:
删除应该相当简单,您已经有了大致的想法:
public Student remove(Student items) {
LinearNode previous = null,
current = head;
// iterate over all the nodes starting at the head, maintaining a reference to the previous node as you go
while (current != null && current.items.compareTo(items) != 0) {
previous = current;
current = current.next;
}
// At this point you have either a) found the Node with matching items or b) not found it
if (current == null) {
// not found in the list
return null;
}
// At this point you know where the Node is, and you have a reference previous node as well
// so it's easy to reattach the linked list to remove the node
if (previous == null) {
// The head node was the match if previous is not set, so make sure to update the head Node accordingly
head = current.next;
}
else {
previous.next = current.next
}
return current.items;
}
使用尝试捕获可疑代码,直到找到导致问题的行。
这会告诉您是否正在寻找正确的地方。
例如:
while (current != null) {
try{//1st level try
if(current.items.compareTo(items) == 0) {
try{ //2nd level try
if(previous == null) {
head = head.next;
return items;
}
else {
previous.next = current.next;
return items;
}
}catch(NullPointerException e ){
StackTraceElement t = e.getStackTrace()[0];
System.out.println("catch lvl 2 at line: " + t.getLineNumber());
}
}
else {
previous = current;
current = current.next;
}
}catch(NullPointerException e){
StackTraceElement t = e.getStackTrace()[0];
System.out.println("catch lvl 1 at line: " + t.getLineNumber());
}
}
编辑:
您可以尝试放置此"try catch"并包装所有主要函数:
try{
...
}catch(NullPointerException e ){
int i=0
for( StackTraceElement t : e.getStackTrace()){
System.out.println("stack[" + i + "]: " + t.getLineNumber());
i++;
}
}
编辑2
public Student remove(Integer studentId)
{
LinearNode previous = null;
LinearNode current = head;
while (current != null) {
//if everything is OK you can remove the 2 ifs
if(current.items == null){
//something is really wrong on insert
}
else if(current.items.getId() == null){
//something is really wrong on insert
}
else if( studentId.compareTo(curent.items.getId()) == 0) {
//return value is curent.items;
if(previous == null) {
head = head.next;
return curent.items;
}
else {
previous.next = current.next;
return curent.items;
}
}
else {
previous = current;
current = current.next;
}
}
//not found!
return null;
}