代码之家  ›  专栏  ›  技术社区  ›  James McMahon

Java 1.4中如何向自定义类添加迭代器的示例?

  •  2
  • James McMahon  · 技术社区  · 7 年前

    包装一个收藏是最好的选择吗?差不多

    public Iterator iterator() {
        return wrappedCollection.iterator();
    }
    

    Iterator it = customClass.iterator();
    while (it.hasNext()) {
        //do stuff
    }
    
    6 回复  |  直到 17 年前
        1
  •  4
  •   matt b    17 年前

    您是否添加了一个如下所示的方法

    public Iterator iterator() {
        return new YourCustomIterator(...);
    }
    

        2
  •  4
  •   Bill the Lizard    17 年前

    如果您只是包装一个集合,那么可以使用转发方法。

    public class Custom implements Collection {
        Collection c; // create an instance here or in the constructor
        ...
    
        // forwarding method
        public Iterator iterator()
        {
            return c.iterator();
        }
    }
    

    不过,我认为最好实现您包装的任何类型的集合接口,而不是迭代器。

        3
  •  1
  •   jiggy    17 年前

    听起来好像您刚刚将这些方法添加到了包含集合的类中。在这种情况下,对象现在也是迭代器。您可能想做的是创建一个实现迭代器的新类,并通过迭代器()方法使用集合的克隆进行实例化。

        4
  •  1
  •   Kathy Van Stone    17 年前

        5
  •  1
  •   Matthew Flaschen    17 年前

    public class IterableTest
    {
        public Iterator iterator()
        {
            return new IteratorTest();
        }
        private class IteratorTest implements Iterator
        {
            public boolean hasNext(){...}
    
            public Object next(){...}
    
            public void remove(){...}
        }
    }
    
        6
  •  1
  •   Karephul    17 年前

    我猜你在找下面这样的东西

    http://karephul.blogspot.com/2009/05/concurrentmodificationexception.html

    &是的,你要寻找的是内部阶级的概念。