使用泛型在LinkedList中使用Java中的空指针异常

时间:2014-11-28 14:25:55

标签: java

    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) + ")";
    }
}

3 个答案:

答案 0 :(得分:2)

使用add方法:

if (first==null) first=last;

last永远不会被初始化。它始终是null因此first始终是null

当您拨打get方法时,请执行以下操作:

first=first.next;

firstnull时,您会获得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)

您的变量lastfirst从未初始化:

Entry<E> first;
Entry<E> last;

因此,在get()方法中,您将在此行中捕获nullPointerException:

first=first.next;