Java Classes - it212 | Data Structures

Download Report

Transcript Java Classes - it212 | Data Structures

Iterator
Summary
Slides by Entesar Al-Mosallam
adopted from Steve Armstrong
LeTourneau University Longview, TX
2007, Prentice Hall
Iterator Interface
--------------------hasNext()
Next()
remove
implements
Separate Iterator class
implements
ListWithIteratorInterface
-----------------------implements .
LinkedListWithIterator Class
.
.
getIterator()
IteratorForLinkedList
implements
ArrayListWithIterator Class
IteratorForArrayList
implements
extends
List
Interface
Interface Iterator
public interface Iterator < T >
{
public boolean hasNext ();
public T next ();
public void remove (); // Optional
method
} // end Iterator
Inner Class Iterator
public interface ListWithIteratorInterface
< T > extends ListInterface < T >
{
public iterator < T > getIterator ();
} // end ListWithListIteratorInterface
public class ArrayListWithIterator < T >
implements ListWithIteratorInterface < T >
{
private T [] list; // array of list entries
private int length;
private static final int
DEFAULT_INITIAL_CAPACITY = 25;
// Constructors here
// Implementations of the methods of the
//ADT list go here;
In Client Class:
ListWithIteratorInterface <String> nameList=
new ArrayListWithIterator <String>();
Iterator < String > nameIterator =
nameList.getIterator();
public Iterator < T > getIterator ()
{
return new IteratorForArrayList ();
} // end getIterator
private class IteratorForArrayList
implements Iterator < T >
{
//implementation of public methods of
// iterator interface
} // end IteratorForArrayList
} // end ArrayListWithIterator
Inner Class Iterator
public interface ListWithIteratorInterface
< T > extends ListInterface < T >
{
public Iterator < T > getIterator ();
} // end ListWithListIteratorInterface
public class LinkedListWithIterator < T >
implements ListWithIteratorInterface < T >
{
private Node firstNode;
private int length;
// Constructors here
// Implementations of the methods of the
// ADT list go here;
In Client Class:
ListWithIteratorInterface <String> nameList=
new LinkedListWithIterator <String>();
Iterator < String > nameIterator =
nameList.getIterator();
public Iterator < T > getIterator ()
{
return new IteratorForArrayList ();
} // end getIterator
private class IteratorForLinkedList
implements Iterator < T >
{
//implementation of public methods of
// iterator interface
} // end IteratorForLinkedList
// Implementation of the private class
// Node (Segment 6.18) goes here.
} // end LinkedListWithIterator