Monday, July 18, 2011

July 18th, 2011

Iterators
enhanced for loop

String [] horsemen = {"war", "famine" , "pestilence", "death" }
for (String horsemen : horsemen )
System.out.println (horseman) ;

There is an
Iterator interface
Iterable interface

Iterator interface defines methods:
- boolean hasNext () : returns true if next() returns an element
- T next()
- boolean remove()

Scanner testScan = new Scanner (~)
while ( scan.hasNext() ) {
String token = testscan.next() ;
/* code to process token */
}

but....

for (String token : testScan ) ! not legal
because Scanner doesn't implement Iterable

Iterable Specifies iterator ()
- iterator returns an object of type Iterator

ArrayList implements both Iterable, Iterator.
-------
ArrayList arrayListOfFoo = new ArrayList ();
for ( Foo refToFoo : arrayListofFoo {
/* do something * /
}

compared to

ArrayList arrayListOfFoo = new ArrayList() ;
Iterator arrayListIter = arrayListOfFoo.iterator () ;
while (arrayListIter.hasNext() ) {
Foo refToFoo = arrayListIter.next() ;
/* Code to do something */
}



Recall collections of MPs
-unorganised rabble (set)
linear order (list)
nonlinear order (Tree)


public void printlistofMPs ( collection all MPs )
{ for (MemberOfParliment one Mp: all MPs )
{ System.out.print;n(oneMP); }
}

Iterable declares

Iterator iterator()
   * return an object of type Iterator

Iterator declares

boolean hasNext() return true iff a call to next() will return an object

T next() return the next object from the collectionl repeared calls to next() will return every element exactly once Order will depend on the type of collection.

void remove () remove the element

Collection extends Iterable

int size() return the number of things in the underlying collection

boolean add (E e) add a thing to the underlying collection

boolean remove (Object o) remove from the underlying collection to the first thing hat is equal to the object provided as a parameter

public interface List extends Collection

void add (int index, E e) add an element at the specified position

E get (int index) Retrieve the element at the specified position

E remove (int index) Remove the element at the specified position.

No comments:

Post a Comment