2016-12-02

posted Dec 2, 2016, 6:53 AM by Samuel Konstantinovich   [ updated Dec 2, 2016, 9:30 AM ]
SuperArray, now with more interfaces! (Iterable)

Your goal is to make your SuperArray work with the for-each loop. 
*The for-each loop only works with classes that implement the Iterable<T> interface.*

This means you need to make your SuperArray implement Iterable<T>, since your SuperArray contains String, we use Iterable<String>. Iterable<String> requires that your super array can upon request, manufacture an Iterator<String> using the iterator() method. Before we can do this, we must make an Iterator class!

The iterator object you make will implement the Iterator<T> interface. 

Note that in order for java to know what an iterator is you will need to:
import java.util.Iterator;

0. Make a new directory in your repository:
MKS21X/02SuperArrayIterator/
Do all work here, and commit regularly. Do not just update your code when you are done!

1. We will first need to create an iterator class that implements Iterator<String>. We will call this class SuperArrayIterator. 

The superArrayIterator needs to know:
-Which SuperArray is it looking at
-Which element is it up to

It needs to have: 
-A constructor to initialize the state of the iterator. 
-Iterator interface methods ( hasNext, next, and remove. See the iterator<T> documentation for more information.) 
-The remove should be unsupported. 

To start, write this as a separate class, we can discuss inner classes after you get it to work.

2. Now work on your SuperArray!
-Make your SuperArray implement Iterable<String>
-Add the iterator() method.  //SORRY! fixed the typo

3. That is all! Test with my class here:
public class Driver{
  public static void main(String[] args) {
    SuperArray data = new SuperArray();
    int i = 0;
    while(i < 26){
      data.add(""+(char)('A'+i%26));
      i++;
    }

    System.out.println(data);
    System.out.println("Standard loop:");

    for(int n = 0; n < data.size(); n++){
      System.out.print(data.get(n)+" ");
    }
    System.out.println();
    System.out.println("for-each loop:");
    for(String s : data){
      System.out.print(s+" ");
    }
  }
}
Comments