1 / 48

Iterators & the Collection Classes

Iterators & the Collection Classes. The Collection Framework classes provided in the JAVA API(Application Programmer Interface) many type of collections like an ArrayList These classes implements the List interface. The Iterator Interface. Iterators.

Download Presentation

Iterators & the Collection Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Iterators & the Collection Classes

  2. The Collection Framework classes provided in the JAVA API(Application Programmer Interface) many type of collections like an ArrayList • These classes implements the List interface The Iterator Interface

  3. Iterators There are 35 methods in the Collections Interface. Several of the methods have to do with the iterator interface.

  4. A key operation of a Collections class is the necessity to traverse and process the data stored in the collection • Therefore, most Collection classes e.g the ArrayList class, implement a special Interface that provides for this – • the Iterator interface. The Iterator Interface

  5. In order to step through a collection in the past we used loops. • The question is : How can any Collection class allow users to loop through say an ArrayList without making sure they do not corrupt the data? • The solution is the use of iterators. The Iterator Interface

  6. Iterator An iterator is an object that enables a user to loop through a collection.

  7. So associated with each class that implements the Collections interface there is an Iterator class. • Each iterator class must implement the iterator interface which consists of methods that we will examine. The Iterator Interface

  8. The following methods are listed in the iterator interface; public interface iterator { T next(); boolean hasnext(); void remove() throws unsupportedException() } Iterator Interface

  9. The ArrayList class ( and others) have a nested class that implements the Iterator interface • The nested class - ArrayIterator implements the iterator interface.. • Let’s look at the code: The Iterator Interface

  10. import java.util.Iterator; // using the iterator in java. util public class ArrayList<T> implements ListADT<T> {protected final int DEFAULT_CAPACITY = 100; private final int NOT_FOUND = -1; protected int rear;protected T[] list; //----------------------------------------------------------------- // Creates an empty list using the default capacity. //-----------------------------------------------------------------public ArrayList() { rear = 0; list = (T[])(new Object[DEFAULT_CAPACITY]); }

  11. //----------------------------------------------------------------- // otherMethods add and remove etc. //----------------------------------------------------------------- public T removeFirst() throws EmptyCollectionException { }// OTHER ARRAYLIST METHODS HERE //----------------------------------------------------------------- // Returns an iterator for the elements currently in this list. //-----------------------------------------------------------------public ArrayIterator<T> iterator() { return new ArrayIterator<T> (list,rear); } Note that we pass rear (rear - stores the index of the last item in the array) And list which is the array of T holding the data }

  12. // this class is nested inside of Arraylist class ArrayIterator<T> implements Iterator<T>{private int count; // the number of elements in the collection private int current; // the current position in the iteration private T[] items; // an array to store the collection//----------------------------------------------------------------- // Sets up this iterator using the specified items. //----------------------------------------------------------------- public ArrayIterator (T[] collection, int size) {items = collection;// store the collection in items count = size; // store size in count current = 0; }

  13. // Returns true if this iterator has at least one more element // to deliver in the iteration. //-----------------------------------------------------------------public booleanhasNext() { return (current < count); } current COUNT

  14. //-----------------------------------------------------------------// Returns the next element in the iteration. If there //are no more elements in this iteration //-----------------------------------------------------------------public T next() { if (! hasNext()) throw new ElementNotFoundException("Element not There"); current++; // increment to next item return items[current - 1]; // return the element} current COUNT

  15. //------------------------------------------------------------- // The remove operation is not supported in this collection. //----------------------------------------------------------- public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); }}

  16. Look at this code in the ArrayList class: // Pre: sents references to the arraylist object ‘”list” and the number of items // Postcondition: an iterator to traverse the arraylisthas been returned the main class public Iterator iterator( ) { return new ArrayInterator(list, count ); } // method iterator This method creates an object of the inner iterator class ArrayInterator( ); and returns it to the main application

  17. Inside the ArrayList class, we have a method to create the array iterator public Iterator iterator( ) { return new ArrayInterator(list, count ); } // method iterator It is called in DatingService when find button is pressed: “List” is the variable for the arraylist of Clients if (e.getActionCommand().equals("FIND")) { // code to get an iteratorArrayIterator<Client> iter = List.iterator();

  18. For the Linked List class, the nested iterator class – • class ListIterator class - will have one field: ListNode<T> cur; // used to traverse list The ListIterator Class

  19. class LinkedIterator<T> implements Iterator { private int count; // the number of elements in the collectionprivate LinearNode<T> curr; // the current position //------------------------------------------------------------- // Sets up this iterator using the specified items. // first will be equal to head, size is # of items currently in list //------------------------------------------------------------- public LinkedIterator (LinearNode<T> first , int size) {curr = first; // where first is head points to first node count = size; } The Iterator Interface -Implementation for a Linked List

  20. // method hasNext returns true as long as //next is not null - allows the iteration over //the collection to continue if there are more //items to process public booleanhasNext() { return cur != null; } The Iterator Interface -Implementation

  21. Pointer to next node in the list head Data next doe ray me null cur Variable to traverse the list

  22. head Data next doe ray me null cur Cur traverses the list

  23. class LinkedIterator implements Iterator private int count; // the number of elements in the collection private LinearNode<T> cur; // the current position public LinkedIterator(LinerarNode<T> first, size ) { cur = first; // sets up cut to point to the beginning of the list – first count -= size; } // constructor //************************************************************* // Precondition: this Iterator is positioned at an element in this Linked Collection. // Postcondition: The element this Iterator was (before this call) positioned at has been //returned, and this Iterator has advanced. //************************************************************* public T next() { T element = cur.data; // get the data cur = cur.getNext(); // advance to the next node return element; // return the element } // method next //************************************************************* // Postcondition: true has been returned if this Iterator is positioned // an element in this Collection. Otherwise, false has been returned. //************************************************************* public boolean hasNext() { return cur != null; // determines if there are more items to processs } // method hasNext //************************************************************* public void remove() { throws unsupported Exception

  24. public class CreatingCollections{ public static void main(String args[]) {// Creates a collection object List <T>list = new ArrayList<T>(); // Uses the add method to add each elementlist.add("This is a String");list.add(new Integer(35));// Get an interator for the input list and step through each //element within the for statement.for (Iteratoriter = list.iterator(); iter. hasNext(); ) {System.out.print(iter.next()); } } }   Results in: This is a String 35

  25. There is also a ListIterator interface which extends Iterator. The description is at this link: • http://www.janeg.ca/scjp/util/iterator.html • It is in java.util and has more methods than the parent interface Iterator ListIterator Interface

  26. Interface ListIterator, which allows a programmer to traverse a List in either direction and make modifications to the underlying List • -- Newer versions of the iterator: ListIterator

  27. Some additional methods in ListIterator: • hasPrevious() returns true if there are more elements in a backward direction • previous() returns the previous element in the List • previousIndex() returns the index of the previous element in the list. ListIterator Interface

  28. /* This is from a 1052 project. List is defined as an ArrayList of ClientsArrayList<Client> List = new ArrayList<Client>();if (e.getActionCommand().equals("FIND")) { // code to get a clientArrayIterator<Client> iter = List.iterator(); while (iter.hasNext()) { client = iter.next(); if(hobby.equalsIgnoreCase(client.getHobby())) response += client.toString() + "\n"; } // close for }//close if /// code to process client } // close else

  29. New with JDK 1.5 is the Iterable interface. It resides in java.lang and has some enhancements • What are the differences between the two (class that implements Iterable and a class that implements Iterator)? • We can make an iterable object have different kinds of iterators? Iterable Interface

  30. class IterableIterator<T> implements Iterable<T> • {     • private Iterator<T> iter;   •  public IterableIterator(Iterator<T> iter) • {  this.iter = iter;    }   •  public Iterator<T> iterator() • {  return iter;     • } • } • Allows different types of iterators to be created

  31. class Tree // creates two iterators {    IterableIterator<Node>depthFirstIterator();    IterableIterator<Node>breadthFirstIterator(); }

  32. But then, how does this work when we use the iterable object in a foreach statement? • How do we specfify which iterator we want to use? • for (Node node: aTree.depthFirstIterator()){} For Each loops with Iterators

  33. And by the way, the only benefit of the previous example is to be able to use a for loop on an iterable collection. • You can just use a while loop when you want to use a different traversal method from the default one, and provide a second iterator() method. Conclusion

  34. In addition, for now the Iterable interface is not backward compatible. Conclusion

More Related