“this”在此代码中完全引用了什么?(What does “this” refer to exactly in this code?)

系统教程 行业动态 更新时间:2024-06-14 17:00:14
“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.

更多推荐

本文发布于:2023-04-18 00:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/2b38840b3ff88abff5f277168faabba1.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在此   代码   code   refer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!