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
尝试制作链表
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
只是一个简单的点
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) + ")";
}
}
答案 0 :(得分:2)
使用add
方法:
if (first==null) first=last;
但last
永远不会被初始化。它始终是null
因此first
始终是null
。
当您拨打get
方法时,请执行以下操作:
first=first.next;
当first
为null
时,您会获得NullPointerException
查看代码的这一部分:
public Entry(E element,Entry<E> to) {
data=element;
next=to;
to=this;
}
最后一句to = this
什么也没做。您没有像预期的那样修改last
。
编辑---
您应该使用last
方法更新add
:
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;
}
答案 1 :(得分:0)
最后没有被设定。它将始终为null。所以首先总是为空。当你打电话到这里时:
public E get() {
Entry<E> temp=first;
first=first.next;
return temp.data;
}
您正试图从空对象中获取下一个值。
答案 2 :(得分:0)
您的变量last
和first
从未初始化:
Entry<E> first;
Entry<E> last;
因此,在get()
方法中,您将在此行中捕获nullPointerException:
first=first.next;