Implement Java Iterator and Iterable in same class?

后端 未结 4 1688
终归单人心
终归单人心 2020-12-13 21:03

I am trying to understand Java Iterator and Iterable interfaces

I am writing this class

class MyClass implements Iterable&         


        
4条回答
  •  孤街浪徒
    2020-12-13 21:17

    You were on track with your first try. MyClass only needs to implement Iterable, which in turn requires you to provide an Iterator implementation to return from Iterable.iterator().

    There's no need to put the MyClassIterator outside of MyClass because in most cases you will never even need to directly use the Iterator (it's used implicitly by the for .. in .. syntax on Iterables), and in all other cases the interface is sufficient unless you actually add additional behavior to the implementation (which you likely won't ever need to do).

    Here's how I'd do it, see comments inlined:

    import java.util.Iterator;
    
    class MyClass implements Iterable{
        public String[] a=null; //make this final if you can
        public MyClass(String[] arr){
            a=arr; //maybe you should copy this array, for fear of external modification
        }
    
        //the interface is sufficient here, the outside world doesn't need to know
        //about your concrete implementation.
        public Iterator iterator(){
            //no point implementing a whole class for something only used once
            return new Iterator() {
                private int count=0;
                //no need to have constructor which takes MyClass, (non-static) inner class has access to instance members
                public boolean hasNext(){
                    //simplify
                    return count < a.length;
                }
                public String next(){
                    return a[count++]; //getting clever
                }
    
                public void remove(){
                    throw new UnsupportedOperationException();
                }
            };
        }
    }
    

提交回复
热议问题