Java中的空引用

时间:2017-11-10 10:33:20

标签: java reference null

在我的main方法中,当我创建一个空的SLList,并调用addLast_iterative()方法时,如果我尝试创建一个null的引用 实例变量'first'(在addLast_iterative()中),然后尝试引用具有相应值的新节点,它不会更改先前的引用'first'来引用新的IntNode对象?我已经得到它的工作,但我很好奇为什么这不会改变'第一'引用新创建的IntNode对象。如果不清楚,可以跳过addLast_iterative(int x)。我注释掉了不起作用的部分,顶部的“if”循环确实有效。换句话说,如果我使用我注释掉的'if'语句,“first”仍将引用Null。感谢

public class SLList {

    private static class IntNode {
        public int item;
        public IntNode next;

        public IntNode(int i, IntNode n) {
            this.item = i;
            this.next = n;
        }
    }

    private IntNode first;
    private int size;


    /* initialize empty SLList */
    public SLList() {
        this.first = null;
        this.size = 0;
    }

    public SLList(int x) {
        this.first = new IntNode(x, null);
        this.size = 1;
    }

    public void addFirst(int x) {
        this.first = new IntNode(x, this.first);
        size += 1;
    }

    public int getFirst() {
        return this.first.item;
    }

    /*************************************************************/
    public void addLast_iterative(int x) {

        this.size += 1;

        if (this.first == null) {
            this.first = new IntNode(x, null);
            return;
        }

        IntNode p = this.first;

        // why does this bottom 'if' statement not work, but the top 
        //does?
        /*if (p == null) {
            p = new IntNode(x, null);
            return;
        }*/

        while(p.next != null) {
            p = p.next;
        }
        p.next = new IntNode(x, null);
    }

    /*************************************************************/


    /*************************************************************/
    public int size() {
        return size;
    }
    /*************************************************************/

    public static void main(String[] args) {
        SLList lst = new SLList();
        lst.addLast_iterative(3);
    }
}

1 个答案:

答案 0 :(得分:-1)

在注释行中,您将新对象分配给引用变量" p"而this.first仍为空。