简体   繁体   中英

How to use super class iterator() in the listIterator() implementation?

I have two classes: MyArrayCollection, that implements Collection, and MyArrayList, that extends MyArrayCollection and implements List. First one has iterator(). How can I use it in the listIterator() realization in the second class? My ugly attempt:

class MyArrayCollection implements Collection<Integer> {
    ...
    class CIterator implements Iterator<Integer> {
        @Override
        public boolean hasNext() {
            return pos < size;
        }

        @Override
        public Integer next() {
            return array[++pos];
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return new CIterator();
    }
    ...
}

class MyArrayList extends MyArrayCollection implements List<Integer> {
    ...
    class CListIterator extends CIterator implements ListIterator<Integer> {
        ...
    }

    @Override
    public ListIterator<Integer> listIterator() {
        return new CListIterator();
    }
    ...
}

I am not sure if I understand your question but I guess you want to use an instance of Iterator<Integer> fetched from the iterator() method. Sure you can, for instace like this :

class CListIterator extends CIterator implements ListIterator<Integer>
{
  private final Iterator<Integer> iterator;
  public CListIterator() {
    super();
    this.iterator = iterator();
  }

  ...
}

And then you could implement the methods from ListInteger using that iterator instance. But the problem is that you need to implement these functionalities:

  • iterate backwards
  • obtain the index at any point
  • add a new value at any point
  • set a new value at that point

And the iterator instance will not probably help you a lot there. For instance the ArrayList.listIterator iterator doesn't use the ArrayList.iterator at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM