iterators & the collection classes

48
1 FO R USERS, TH E LinkedC ollection and A rrayListclasses C ontain A n ITER A TO R CLASS . Iterators & the Collection Classes

Upload: samson-meyers

Post on 03-Jan-2016

34 views

Category:

Documents


1 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Iterators & the Collection Classes

1

FOR USERS, THE LinkedCollection and ArrayList classes

Contain An ITERATOR CLASS.

Iterators & the Collection Classes

Page 2: 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

Page 3: Iterators & the Collection Classes

3

There are 35 methods in the Collections Interface.

Several of the methods have to do with the iterator interface.

Page 4: Iterators & the Collection Classes

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.

Page 5: Iterators & the Collection Classes

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.

Page 6: Iterators & the Collection Classes

6

Iterator

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

Page 7: Iterators & the Collection Classes

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.

Page 8: Iterators & the Collection Classes

8

The following methods are listed in the iterator interface;

public interface iterator {

T next();

boolean hasnext();

void remove() throws unsupportedException()}

Page 9: Iterators & the Collection Classes

9

public interface Iterator { // Precondition: this Iterator is positioned at

// an element in the Collection. //Postcondition: the element where this //Iterator was positioned at has been //returned, and this Iterator has been //incremented.

T next( );

Page 10: Iterators & the Collection Classes

10

// Postcondition: true is returned if

// this Iterator is positioned at an element //in the Collection. Otherwise, false is // returned.

boolean hasNext( );

Page 11: Iterators & the Collection Classes

11

// Postcondition: No longer supported – throws // an exception void remove( ) throws Unsupported Exception() } // interface Iterator

Page 12: Iterators & the Collection Classes

12

The ArrayList class ( and others) have a nested class that implements the Iterator interface

The nested class - The nested class - ArrayIterator implements the iterator interface..

Let’s look at the code:Let’s look at the code:

Page 13: Iterators & the Collection Classes

13

import java.util.Iterator; import java.util.Iterator; // using the iterator in java. util// using the iterator in java. util

public class ArrayList<T> implements ListADT<T> 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; protected T[] list; //----------------------------------------------------------------- // Creates an empty list using the default capacity. //----------------------------------------------------------------- public ArrayList()public ArrayList() { { rear = 0; rear = 0; list = list = (T[])(new Object[DEFAULT_CAPACITY]);(T[])(new Object[DEFAULT_CAPACITY]); } }

Page 14: Iterators & the Collection Classes

14

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

And And list list which is the array of T holding the datawhich is the array of T holding the data } }

Page 15: Iterators & the Collection Classes

15

Page 16: Iterators & the Collection Classes

16

8 20 30 60 90 89 34

currentcurrent COUNT

Page 17: Iterators & the Collection Classes

17

8 20 30 60 90 89 34

currentcurrent COUNT

Page 18: Iterators & the Collection Classes

18

Page 19: Iterators & the Collection Classes

19

Look at this code in the ArrayList class:Look at this code in the ArrayList class:// Pre: // Pre: sents references to the arraylist objectsents references to the arraylist object‘”‘”list” and the number of itemslist” and the number of items// Postcondition// Postcondition: an iterator to traverse the arraylist has been returned the main class: an iterator to traverse the arraylist has 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( );This method creates an object of the inner iterator class ArrayInterator( ); and returns it to the main applicationand returns it to the main application

Page 20: Iterators & the Collection Classes

20

USER CANNOT DO THIS from an outside class:

Arrayiterator itr = new Array Iterator( );

WHY NOT???

Page 21: Iterators & the Collection Classes

21

The Array Iterator class is an inner class and therefore has

private visibility: inaccessible

outside of the ArrayList class. The only class that can access private inner class ArrayIterator is the ArrayList class

Page 22: Iterators & the Collection Classes

22

THE SOLUTION: A NEW METHOD IN THE ArrayList CLASS:

Page 23: Iterators & the Collection Classes

23

public Iterator iterator( ) { return new ArrayInterator(list, count ); } // method iterator

 

Inside the ArrayList class, we have a method to Inside the ArrayList class, we have a method to create the array iterator create the array iterator

It is called in DatingService when find button is pressed:It is called in DatingService when find button is pressed: “ “List” is the variable for the arraylist of ClientsList” is the variable for the arraylist of Clients

if (e.getActionCommand().equals("FIND"))if (e.getActionCommand().equals("FIND")) { { // code to get an iterator // code to get an iterator ArrayIterator<Client> iter = List.iterator(); ArrayIterator<Client> iter = List.iterator();

Page 24: Iterators & the Collection Classes

24

» For the Linked List class, the nested iterator class –

» class ListIterator class - will have one field:

ListNode<T> cur; // used to traverse list

Page 25: Iterators & the Collection Classes

25

class LinkedIterator<T> implements Iterator { private int count; // the number of elements in the collection private 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; }

Page 26: Iterators & the Collection Classes

26

// 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 boolean hasNext() { return cur != null;}

Page 27: Iterators & the Collection Classes

27

// This method extracts the data from the node and /then advances next to the next node. public T next( ) { // throw an exception if no more items T element = cur.data; // get the data // advances next to the next node cur= cur.getNext(); return element; // returns the data } // method next

Page 28: Iterators & the Collection Classes

28

public class LinkedList { // LinkedList methods listed here //nested Iterator class below

private class LinkedIterator { // methods: next(), hasNext(), remove() } // close inner class LinkedIterator

} // class LinkedList

Page 29: Iterators & the Collection Classes

29

raydoe me null

headData next

cur

Variable to traverse the list

Pointer to next node in the list

Page 30: Iterators & the Collection Classes

30

raydoe me null

head

cur

Data next

Cur traverses the list

Page 31: Iterators & the Collection Classes

31

RETURNED: “ray” – as an Object

Page 32: Iterators & the Collection Classes

32

USER CANNOT DO THIS from an outside class:

Linkedterator itr = new LinkedIterator( );

WHY NOT???

Page 33: Iterators & the Collection Classes

33

The LinkedIterator class is an inner class and therefore has

private visibility: inaccessible

outside of the LinkedList class. The only class that can access private inner class LinkedIterator is the LinkedList class

Page 34: Iterators & the Collection Classes

34

THE SOLUTION: A NEW METHOD IN THE LinkedList CLASS:

Page 35: Iterators & the Collection Classes

35

// Postcondition: a LinkedList over this LinkedCollection has been returned. public Iterator iterator( ) { return new LinkedInterator(head,count ); } // method iterator This method creates an object of the inner iterator class

LinkedInterator( ); and returns it to the main application

Page 36: Iterators & the Collection Classes

36

WHAT IS RETURNED?

A REFERENCE TO AN OBJECT of the LinkedIterator inner Class nested INSIDE THE LinkedList CLASS

Page 37: Iterators & the Collection Classes

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

Page 38: Iterators & the Collection Classes
Page 39: Iterators & the Collection Classes

39

» 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

Page 40: Iterators & the Collection Classes

40

» 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:

Page 41: Iterators & the Collection Classes

41

» 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.

Page 42: Iterators & the Collection Classes
Page 43: Iterators & the Collection Classes

43

» 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?

Page 44: Iterators & the Collection Classes

44

» 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

Page 45: Iterators & the Collection Classes

45

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

Page 46: Iterators & the Collection Classes

46

» 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()){}

Page 47: Iterators & the Collection Classes

47

» 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.

Page 48: Iterators & the Collection Classes

48

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