(转载)ArrayList.this 类名.this何意

参考原文链接https://blog.csdn.net/jiachunchun/article/details/90235767

ArrayList的源码中,有一个实现了Iterator接口的内部类Itr,其中有两个elementData变量,一个是内部类的属性,一个是外部类的,那么外部类的就必须标识为ArrayList.this.elemtData

注意,不是this.elementData,因为外部类的对象是不能调用内部类的,所以只能用类名.this来区别内部类和外部类的属性。

 1     //内部类
 2     private class Itr implements Iterator<E> {
 3         transient Object[] elementData;
 4      
 5         @SuppressWarnings("unchecked")
 6         public E next() {
 7             //同名变量
 8             Object[] elementData = ArrayList.this.elementData;
 9         }
10     }

内部类中如果有相同的变量名字时需要根据此来区分

class one{
    String name = "one";
    class two{
        String name = "two";
        String test = this.name+" "+one.this.name;//this.name是two的name   one.this.name是外部one的name
    }
}

public class Test{
one test = new one();
    System.out.println(test.new two().test);

}

运行结果为two one 说明在内部类中使用相同名字的外部变量需要  类名.this.变量名



原文地址:https://www.cnblogs.com/9527s/p/11431723.html