12-13-2013

posted Dec 13, 2013, 9:21 AM by Samuel Konstantinovich   [ updated Dec 13, 2013, 9:21 AM ]
Our goal is to make MyList iterable. 

1. Iterators cannot have primitive types, so we will use the Integer object to handle our int list. This is why our Iterable<> and Iterator<> has Integer inside them.

2. The modification to MyList is very small. We make one method, iterator() that returns an Iterator<Integer>. 




import java.util.*;
public class MyList implements Iterable<Integer>{
    private int [] data;
    private int size;

    public Iterator<Integer> iterator(){
        /*the iterator needs a copy of the object you are 
          iterating over, so we pass it a refernece to this*/
        return new MyListIterator(this);
    }
    public MyList(){
        data = new int[10];
        size=0;
    }
    /* the rest of MyList not shown*/
}


NOW YOU WRITE THE ITERATOR PART:


import java.util.*;
public class MyListIterator implements Iterator<Integer>{
    MyList data;
    int place;

    public MyListIterator(MyList L){
        data = L;
        place = 0;
    }

    public boolean hasNext(){
        /* to be implemented by you!*/
        return false;
    }

    public Integer next(){
        /* to be implemented by you!*/
        return null;
    }

    public void remove(){
        /*since we don't want to implement this...*/
        throw new UnsupportedOperationException();
    }
}

Comments