Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the incomplete StringIterator class below that represents an indirect a

ID: 3665562 • Letter: C

Question

Consider the incomplete StringIterator class below that represents an indirect access iterator used to step through the characters in a string. For this question, assume Java's Iterator interface is non-generic as shown:

public class StringIterator implements Iterator { ... public StringIterator( ... ) { ... } public boolean hasNext() { ... } public Character next() { ... } public void remove() { throws new UnsupportedOperationException(); } }

Complete the class above in the 5 areas indicated with "..." so that the methods behave as specified for the Iterator interface using an indirect access approach.

Explanation / Answer

package com.he.capillary;

import java.util.Iterator;

public class StringIterator implements Iterator {

   private String str;
   private int index;

   public StringIterator(String str) {
       this.str = str;
       this.index = str.length();
   }

   public boolean hasNext() {
       if (index != 0)
           return true;
       return false;
   }

   public Character next() {
       char ch = str.charAt(str.length() - index);
       index--;
       return ch;
   }

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


Testing Code :

StringIterator si = new StringIterator("abcd");
       while(si.hasNext()){
           System.out.println(si.next());
       }