Interview: Design an iterator for a collection of collections

前端 未结 6 1082
Happy的楠姐
Happy的楠姐 2020-12-29 12:09

Design an iterator for a collection of collections in java. The iterator should hide the nesting, allowing you to iterate all of the elements belonging to all of the collect

6条回答
  •  自闭症患者
    2020-12-29 12:16

    if all you have to work with is the java Iterator: which just have hasNext(), next() and remove(), i figured you have to go around it.

    Process it as you will process a 2D array, that is, with an outer and inner loop, because they have same "arrangement" but different datatype. As you process, you transfer them to a new collection.

    so maybe a private method:

        private void convertToSingleCollection()
        {
    
    
             while("column")
             {
                //convert the "column" to an arra
    
    
               for( "Row")
               {
                //add to newCollection here
               }
    
              //remove the processed column from CollectionOFcollection
             } 
        }
        //call the above method in your constructor
    
    
        public iterator Iterator()
        {
           newCollection.iterator();
        }
    
        public boolean hasNext()
        {
           return Iterator().hasNext()
        }
    
        public T next()
        {
           if(!hasNext())
           {
            //exception message or message
           }
           else
               //return "next"
        }
    

    end

    I hope this helps. There should be other ways to solve it i guess.

提交回复
热议问题