How to write an iterator for an iterator of iterators?
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers

 Q1. How to write an iterator for an iterator of iterators?Core Java
Ans. CustomArrayList myarrayList = new CustomArrayList();
      myarrayList.add("Value 1");
      myarrayList.add("Value 2");
      myarrayList.add("Value 3");
      
      for (String string : myarrayList) {
         System.out.println(string);
      }



package sample.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CustomArrayList implements Iterable {

   private ArrayList mylist = new ArrayList();

   public void add(T t) {
      this.mylist.add(t);
   }

   @Override
   public Iterator iterator() {
      return new CustomIterator(mylist);
   }

   class CustomIterator implements Iterator {

      private int indexPosition = 0;
      private List internalList;

      public CustomIterator(List internalList) {
         this.internalList = internalList;
      }

      @Override
      public boolean hasNext() {
         if (internalList.size() >= indexPosition 1) {
            return true;
         }
         return false;
      }

      @Override
      public E next() {
         E val = internalList.get(indexPosition);
         indexPosition ;
         return val;
      }

   }

}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     iterator     Asked in 1 Companies


Related Questions

  What is an Iterator?
  What are few iterator classes provided by Java ?
 What are fail-fast Iterators ?
 Is Iterator a class ?
 How Spliterator in Java 8 different than iterator ?
 Which is better in terms of performance - Iterator or Spliterator ?
 What are the cursors available in Java ?
 What is the difference between Enumeration and Iterator ?
 Why iterators of an array list are fail fast ?
 How can i split a linked list in two parts in java 8?



Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: