Docsity

Understanding Iterators and Linked Lists in Java, Slides of Computer Science

Partial preview of the text

Download Understanding Iterators and Linked Lists in Java and more Slides Computer Science in PDF only on Docsity!

Iterators

An iterator permits you to examine

the elements of a data structure one

at a time.

Iterator Methods

Iterator ix = x.iterator();

constructs and initializes an iterator to

examine the elements of x;

constructed iterator is assigned to ix

you must define the method iterator

in the class for x

Optional Iterator Method

ix.remove()

removes last element returned by

ix.next()

throws UnsupportedMethodException if

method not implemented

throws IllegalStateException if ix.next()

not yet called or did not return an

element

Using An Iterator

Iterator ix = x.iterator();

while (ix.hasNext())

examine(ix.next());

vs

for (int i = 0; i < x.size(); i++)

examine(x.get(i));

Java’s Array Linear List Class

java.util.ArrayList

Cadillac version of our

ArrayLinearListWithIterator

Linked Representation

• list elements are stored, in memory,

in an arbitrary order

• explicit information (called a link)

is used to go from one element to

the next

Linked Representation

pointer (or link) in e is null

c a e d b

use a variable firstNode to get to the

first element a

firstNode

Normal Way To Draw A Linked List

link or pointer field of node

data field of node

a b c d e

null

firstNode

Node Representation

package dataStructures;

class ChainNode

{

// package visible data members Object element; ChainNode next;

// constructors come here

}

next element

Constructors Of ChainNode

ChainNode() {}

null null

null element

next element

ChainNode(Object element)

{this.element = element;}

ChainNode(Object element, ChainNode next)

{this.element = element; this.next = next;}

get(1)

checkIndex(1);

desiredNode = firstNode.next; // gets you to second node

return desiredNode.element;

a b c d e

null

firstNode

get(2)

checkIndex(2);

desiredNode = firstNode.next.next; // gets you to third node

return desiredNode.element;

a b c d e

null

firstNode

NullPointerException

desiredNode = firstNode.next.next.next.next.next.next; // gets the computer mad // you get a NullPointerException

a b c d e

null

firstNode

Remove An Element

remove(0)

a b c d e

null

firstNode

firstNode = firstNode.next;