[英]Null pointer exception in Java at LinkedList using generics
public class List_manager<E> {
Entry<E> first;
Entry<E> last;
public void add(E element) {
Entry<E> e=new Entry(element,last);
if (first==null) first=last;
}
public E get() {
Entry<E> temp=first;
first=first.next;
return temp.data;
}
public boolean isEmpty() { return first==null; }
private static class Entry<E> {
Entry<E> next;
E data;
public Entry(E element,Entry<E> to) {
data=element;
next=to;
to=this;
}
}
}
//now the main class
Trying to make a linkedlist 试图建立一个链表
public class Main {
public static void main(String[] args) {
Point p1=new Point(0,0); //
Point p2=new Point(12,5);
Point p3=new Point(43,12);
List_manager<Point> l=new List_manager<Point>();
l.add(p1);
l.add(p2);
l.add(p3);
System.out.println(l.get()); // here is an error occurs
System.out.println(l.get());
}
}
// Point
Just a simple point 简单一点
public class Point {
double x;
double y;
public Point(double x,double y) {
this.x=x;
this.y=y;
}
public String toString() {
return "("+Double.toString(x) + " , " + Double.toString(y) + ")";
}
}
In add
method you do: 在
add
方法中,您可以执行以下操作:
if (first==null) first=last;
But last
is never initialized. 但是
last
永远不会被初始化。 It's allways null
an thus first
is allways null
. 它始终为
null
,因此first
始终为null
。
When you call get
method, yo do: 当您调用
get
方法时,您get
执行以下操作:
first=first.next;
As first
is null
you get the NullPointerException
由于
first
为null
您将获得NullPointerException
Look a this part of your code: 看一下这段代码:
public Entry(E element,Entry<E> to) {
data=element;
next=to;
to=this;
}
the last sentence to = this
does nothing. to = this
的最后一句话什么也没做。 You are not modifying last
as it seems you expect. 您没有像您期望的那样
last
修改。
EDIT --- 编辑-
You should update last
in add
method: 您应该在
add
方法中last
更新:
public void add(E element) {
Entry<E> e = new Entry(element, null);
if (last != null) { last.next = e; }
last = e;
if (first == null) first = last;
}
Last is not being set. 最后未设置。 It will always be null.
它将始终为null。 So first will always be null.
因此first将始终为null。 When you call get here:
致电时到达此处:
public E get() {
Entry<E> temp=first;
first=first.next;
return temp.data;
}
You are trying to grab the next value from a null object. 您试图从空对象获取下一个值。
Your variables last
and first
has never been initialised: 您的变量
last
和first
从未被初始化:
Entry<E> first;
Entry<E> last;
So in your get()
method you will catch a nullPointerException in this line: 因此,在您的
get()
方法中,您将在此行中捕获nullPointerException:
first=first.next;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.