简体   繁体   English

如何在listIterator()实现中使用超类iterator()?

[英]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. 我有两个类:实现集合的MyArrayCollection和扩展MyArrayCollection并实现List的MyArrayList。 First one has iterator(). 第一个有iterator()。 How can I use it in the listIterator() realization in the second class? 如何在第二个类的listIterator()实现中使用它? 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. 我不确定我是否理解您的问题,但我想您想使用从iterator()方法获取的Iterator<Integer>实例。 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. 然后,您可以使用该迭代器实例实现ListInteger的方法。 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. 例如, ArrayList.listIterator迭代器根本不使用ArrayList.iterator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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