鍍金池/ 問(wèn)答/Java  網(wǎng)絡(luò)安全/ ArrayList內(nèi)部類訪問(wèn)其成員變量的問(wèn)題

ArrayList內(nèi)部類訪問(wèn)其成員變量的問(wèn)題

下面是ArrayList的迭代器源碼,我注意到這兩行

 Object[] elementData = ArrayList.this.elementData;
 expectedModCount = modCount;

第一行用的是標(biāo)準(zhǔn)的內(nèi)部類訪問(wèn)外部類成員變量的方法,為何第二行則是直接用變量名,沒(méi)有加“ArrayList.this”?
為何modCount不需要加“ArrayList.this”?不加也能成?

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @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];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
回答
編輯回答
陪她鬧

因?yàn)?ItrArrayList 的內(nèi)部類,內(nèi)部類想要訪問(wèn)外部類的非靜態(tài)成員,最保險(xiǎn)的寫法是 外部類.this.成員名,這樣寫能夠保證當(dāng)內(nèi)部類哪天出現(xiàn)了一個(gè)同名的成員時(shí),不會(huì)被弄混。

2018年3月26日 19:09
編輯回答
何蘇葉

謝邀。

ArrayList.this.modCount更合適些,好在Itr里沒(méi)有modCount這個(gè)成員,否則就有歧義了。

如果編譯警告設(shè)置得嚴(yán)格些,例如Eclipse在Errors/Warnings里把Unqualified access to instance field打開(kāi),那么expectedModCount = modCount;會(huì)報(bào)編譯警告的,只有寫成this.expectedModCount = ArrayList.this.modCount;才會(huì)把警告去掉。

2017年12月19日 22:06