自定义类中的java.lang.NullPointerException
我希望在一个简单的链表类中实现一个基于队列的方法,而不使用自定义类中的java.lang.NullPointerException,java,nullpointerexception,linked-list,Java,Nullpointerexception,Linked List,我希望在一个简单的链表类中实现一个基于队列的方法,而不使用java.util 当我通过enqueue方法调用List类中的addEnd方法时,我会收到一个java.lang.NullPointerException,尽管我需要第二个元素 我可以采取哪种解决方案 节点类 public class Node { private int value; private Node next; public Node(int val) { value = val;
java.util
当我通过enqueue方法调用List类中的addEnd方法时,我会收到一个java.lang.NullPointerException
,尽管我需要第二个元素
我可以采取哪种解决方案
节点类
public class Node {
private int value;
private Node next;
public Node(int val) {
value = val;
}
public Node(int val, Node next) {
value = val;
this.next=next;
}
public Node(Node next) {
this.next=next;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void displayNode() {
System.out.print(" "+value+" ");
}
}
我的界面
public interface MyQueue {
void enqueue(int oVal);
int dequeue();
}
名单
public class List {
private Node first;
private Node last;
private int counter;
public List() {
first = null;
last = null;
}
public boolean isEmpty() {
return first==null;
}
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first = n1;
} else {
last.setNext(n1);
last = n1;
}
}
public int deleteStart() {
int temp = first.getValue();
if(first.getNext() == null){
last = null;
first = first.getNext();
}
return temp;
}
public void displayList() {
Node current = first;
while(current != null) {
current.displayNode();
current = current.getNext();
}
System.out.println("");
}
public int size() {
return counter;
}
}
排队
public class Queue implements MyQueue {
private List listQ;
public Queue() {
listQ = new List();
}
public boolean isEmpty() {
return listQ.isEmpty();
}
public void enqueue(int oVal) {
listQ.addEnd(oVal);
}
public int dequeue() {
return listQ.deleteStart();
}
public void displayQueue() {
System.out.print("Queue ");
listQ.displayQueue();
}
}
public class App {
public static void main(String[] args) {
Queue q1 = new Queue();
System.out.println("Two insertions");
q1.enqueue(4);
q1.enqueue(64);
q1.displayQueue();
System.out.println("Insert at the end : ");
q1.enqueue(23);
q1.displayQueue();
System.out.println("Delete an element at the begining of the queue");
q1.dequeue();
q1.displayQueue();
}
}
插入到空列表时,需要设置最后一个引用。NullPointerException是因为您在设置它之前使用了last。@pens-fan-69所说的是真的。我想补充一下。为了使代码正常工作,您所要做的就是确保在第一次插入期间将last设置为first:
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first=last=n1;
} else {
last.setNext(n1);
last = n1;
}
}
我试着在在线编译器中运行代码,它可以工作:欢迎使用SO:SE。无需提供定位和修复NPE的所有代码。运行调试器,找到空的对象,理解为什么它是空的(在这个阶段,您可以在这里寻求帮助)。再见,非常感谢!下次我会照你说的去做