Java – rewrite the same method twice from the same class

I understand how the iterator () method works with the ArrayList class In the ArrayList class, I found that the iterator () method was rewritten twice from the same class abstractlist

public Iterator<E> iterator() {
    return new Itr();         // Itr is an inner private class of 
                               //   ArrayList which 
                              // implements Iterator interface .
}

public Iterator<E> iterator() {
        return listIterator();
    }

But how is that possible? There should be a defined error I'm confused

Solution

The first iterator () method you see belongs to the ArrayList class, but the second does not

It belongs to the sublist class, which is the internal class of ArrayList:

private class SubList extends AbstractList<E> implements RandomAccess {
    ...
    public Iterator<E> iterator() {
        return listIterator();
    }
    ...
}

Therefore, it will not be overridden twice by the same class Each class will be covered once

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>