Java: this keyword preceded by class name

旧城冷巷雨未停 提交于 2020-01-15 07:16:12

问题


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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/24947750/java-this-keyword-preceded-by-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!