Reputation: 2079
I was going through the following code which is a linked-list implementation using a static nested class:
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/code/LinkedList.java
One line I wasn't able to comprehend was:
public boolean contains(AnyType x)
{
**for(AnyType tmp : this)**
if(tmp.equals(x)) return true;
return false;
}
How's it that "this" here allows us to traverse the data that's stored inside each Node?
Upvotes: 0
Views: 83
Reputation: 7956
Because this
in this case is an Iterable
(more specifically, a LinkedList
).
The for-each
loop introduced in Java 5, is syntactic sugar for calling the Iterator
of the Iterable
. In your example case, the code is equivalent with
for (Iterator<AnyType> i = this.iterator(); i.hasNext(); ) {
if (i.next().equals(x)) return true;
}
Upvotes: 1