如何/在何处实现接口

时间:2014-05-10 02:41:04

标签: java eclipse interface

当我尝试在eclipse中编译我的代码时,它说“必须实现接口DataStructureIterator扩展java.util.Iterator.remove()”请帮助,我不知道在哪里实现它并且它在连续循环中失败。

public class DataStructure {

    private final static int SIZE = 15;


    private int [] arrayOfInts = new int [SIZE];


    public DataStructure () 
    {
        for ( int i = 0; i < SIZE; i++ )
        {
            arrayOfInts[i] = i;
        }   
    }
    public void printEven()
    {

        DataStructureIterator iterator = this.new EvenIterator();

        while (iterator.hasNext())
        {
            System.out.println();
        }
    }

    interface DataStructureIterator extends java.util.Iterator<Integer> 
    { 

    } 



    private class EvenIterator implements DataStructureIterator 
    {

        private int nextIndex = 0;

        public boolean hasNext() {

            return (nextIndex <= SIZE - 1);
        }        

        public Integer next() 
        {               
            Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);

            nextIndex += 2;
            return retValue;
        }
    }

1 个答案:

答案 0 :(得分:3)

EvenIterator被声明为(间接)实现Iterator<Integer>接口,因此必须实现the Iterator.remove method。也就是说:它必须提供一个名为remove的公共方法,它返回void并且不会被声明为抛出任何已检查的异常。

如果您不希望EvenIterator支持元素删除,您可以写一下:

public void remove()
{
    throw new UnsupportedOperationException();
}