【发布时间】:2021-01-25 20:32:09
【问题描述】:
当我对我的MyStack 类的pop 和peek 方法进行单元测试时,我遇到了一个与我的节点类的getData 方法相关的NullPointerException。
我不知道为什么,我想知道是否有人对如何修复它有任何想法并使其没有NullPointerException。我尝试编辑节点的工作方式以及getData 本身的工作方式,但找不到解决方案,因此无法找出问题所在。任何帮助将不胜感激
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
public Node<E> head;
public int nodeCount = 0;
public static void main(String args[]) {
}
public E peek() {
return head.getData();
}
public E pop() {
if (nodeCount == 0) {
throw new EmptyStackException();
}
E item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head == null && nodeCount == 0) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
int count = 0;
Node<E> current = new Node<E>(head.getData());
while (current.getData() != o) {
current.getNext();
count++;
}
return count;
}
}
public class Node<E>
{
public E data;
public Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return this.data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
【问题讨论】:
标签: java nullpointerexception stack nodes