将“this”分配给Java中的引用变量

时间:2017-04-23 03:08:15

标签: java list

我正在尝试使用递归方法在单链表中完成addLast方法,但是,代码给出了list.size()= 2和list.getFirst()= 5的错误输出。应该是由于行

SLList p=this;

似乎改变p引用也改变了“this”引用,这对我来说不是那么逻辑。谁能提供一些有关这方面的细节? THX

public class SLList {
public class IntNode {
    public int item;
    public IntNode next;
    public IntNode(int i, IntNode n) {
        item = i;
        next = n;
    }
}

private IntNode first;

public SLList(int x) {
    first = new IntNode(x, null);
}

/** Adds an item to the front of the list. */
public void addFirst(int x) {
    first = new IntNode(x, first);
}

/** Retrieves the front item from the list. */
public int getFirst() {
    return first.item;
}

/** Adds an item to the end of the list. */
public void addLast(int x) {

    SLList p = this;
    if (p.first. next == null) {
        p.first.next = new IntNode (x, null);
    }

    else {
        p.first = p.first.next;
        p.addLast(x);
    }

}

/** Returns the number of items in the list using recursion. */
public int size() {
    /* Your Code Here! */
    SLList p = this;
    if (p.first == null) {
        return 0;
    }
    else if (p.first.next == null){
        return 1;
    }

    else {
        p.first = p.first.next;
        return 1 + p.size();
    }
}

public static void main (String[] args) {
    SLList list=new SLList (5);
    list.addFirst(10);
    list.addFirst(15);
    list.addLast(17);
    System.out.println(list.getFirst());
    System.out.println(list.size());

}

}

4 个答案:

答案 0 :(得分:4)

问题与this的分配无关。没有什么可以改变this。周期。

(但事情可以改变this引用的对象的状态。)

真正的问题在于您实施size方法。您的size方法导致列表发生变化。它不应该。在您的情况下,更改会导致:

  • size()方法返回错误的值
  • 后续getFirst()次调用以返回错误的值。

我不确切地说出错误的位置,但你应该能够通过消除过程自己发现。 (或者,如果失败,请使用调试器并尝试观察列表的更改位置。)

答案 1 :(得分:1)

您的算法存在的问题比您想象的要大。 size()不正确。如果您意识到需要计算列表中IntNode个对象的数量,则可以解决此问题。同样,所有其他方法都需要操纵IntNode个对象。

答案 2 :(得分:0)

SLList p = this;

p引用相同的SLList对象。如果您对' p'进行任何更改然后它也会发生在这个',因为引用类型(不是值类型)。

声明

p.first = p.first.next;

当您拨打“addLast”时,会更改对第一个的引用。方法。您丢失了对第一个项目的引用。

如果删除该行

list.addLast(17);

在main方法中,您将看到正确的答案。问题在于这种方法。

按如下方式更改方法,并在下面添加新方法。

/** Adds an item to the end of the list. */
public void addLast(int x) {
    addLast(x, this.first);
}

private void addLast(int x, IntNode node){
    if(node.next == null){
        node.next = new IntNode (x, null);
    }else {
        node = node.next;
        addLast(x, node);
    }
}

然后你不会丢失对第一项的引用,现在它可以正常工作,

答案 3 :(得分:0)

实现中的问题是addLast和size方法首先改变字段变量的值。

this分配给某个变量或直接使用并不重要。 因为将this分配给某个变量不会创建新的this对象,而是分配对该变量的引用。

因此,您应首先将first字段变量的值复制到某个局部变量,然后对其进行迭代。这样,first将不会更改。

提示:不要更改第一个变量引用。 您的addLast()size()更改了first的错误值。 问题出在这一行。     p.first = p.first.next;