Reputation: 3542
I find a snippet in ArrayList.java from jdk 8:
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
The line: Object[] elementData = ArrayList.this.elementData;
looks strange to me.
I think ArrayList.this
is equivalent to this
here. Am I right? If there's a difference, what's the benefit of using ArrayList.this
over this
?
Upvotes: 2
Views: 911
Reputation: 2896
That method is inside the private class Itr, which is the inner class of ArrayList. So basically if we want to access the instance variable of outer class we have to do "Class.this" instead of just "this" because "this" would access the current class and not the parent class.
Upvotes: 0
Reputation: 326
When your code is in an inner class, then this points to the inner class, so you need to disambiguate. Therefore ArrayList.this will mean the ArrayList instead of the inner class which in this case I assume to be an Iterator.
Upvotes: 0
Reputation: 280102
The code you see is inside the class Itr
which is an inner class of ArrayList
. The notation
ArrayList.this.elementData
is used to refer to the enclosing ArrayList
instance's field named elementData
. In this case, simply using this.elementData
would be enough. But if your inner class Itr
declared a member named elementData
, you would need the other notation to disambiguate between ArrayList
's member or Itr
's member.
Upvotes: 2
Reputation: 533660
If there's a difference, what's the benefit of using ArrayList.this over this
An Inner class has a reference to an outer class. To use the outer class this
you put the class of the outer class before it.
Note: In this case this
is an Iterator and doesn't have a field called elementData
Upvotes: 4