“this”在此代码中完全引用了什么?(What does “this” refer to exactly in this code?)
public CharList(CharList l)
{
// Whatever method your CharList provides to get the
// first node in the list goes here
CharNode pt = l.head();
// create a new head node for *this* list
CharNode newNode = new CharNode();
this.head = newNode;
// Go through old list, copy data, create new nodes
// for this list.
while(pt != null)
{
newNode.setCharacter(pt.getCharacter());
pt = pt.getNext();
if (pt != null)
{
newNode.setNext(new CharNode());
newNode = newNode.getNext();
}
}
}
我认为这用于引用对象A,如“A.addElement(car);”,但在这种情况下我不知道这是指什么...而且我没有看到做的重点:this.head = newNode; 因为this.head永远不会再使用。
public CharList(CharList l) { // Whatever method your CharList provides to get the // first node in the list goes here CharNode pt = l.head(); // create a new head node for *this* list CharNode newNode = new CharNode(); this.head = newNode; // Go through old list, copy data, create new nodes // for this list. while(pt != null) { newNode.setCharacter(pt.getCharacter()); pt = pt.getNext(); if (pt != null) { newNode.setNext(new CharNode()); newNode = newNode.getNext(); } } }I thought that this is used to refer to the Object A as in "A.addElement(car);", but in this case I don't know what this refers to... And I don't see the point in doing: this.head = newNode; since this.head is never used again.
最满意答案
this指的是CharList的当前实例, this.head指的是实例字段head 。 如果没有具有相同名称的局部变量,则可以放弃this关键字以访问实例字段。
this refers to the current instance of CharList, and this.head refers to the instance field head. You can discard this keyword to access instance fields if there are no local variables with the same name.
更多推荐
发布评论