0
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.

4

4 回答 4

3

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.

于 2013-03-30T21:32:00.613 回答
1

The docs explain what this is:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

The keyword this refers to the current instance of CharList. It is useful for referring to variables that may share the same at class level, otherwise it can be omitted.

Here, no local variable head does not appear in the constructor of CharList, so can be written as:

head = newNode;
于 2013-03-30T21:31:12.303 回答
0

this.head is never used again.

Since head is a member variable of the class, the value set in the constructor will be used in other methods of the class.

于 2013-03-30T21:34:07.920 回答
0

Possible duplicate of What is the meaning of "this" in Java?, but anyway:

It's a reference to the specific instance of the object you're working with. So, if I have (going to write this in C#, sorry):

public class MyObject
{
    public MyObject(string AString) 
    {
         MyString = AString;
    }

    private string MyString;

    public string WhatsMyStringCalled()
    {
         return this.MyString;
    }
}

If I were to construct an instance of MyObject, I would expect WhatsMyStringCalled to return the MyString property associated with that particular instance.

于 2013-03-30T21:34:29.627 回答