• Tidak ada hasil yang ditemukan

PPT Slide 1

N/A
N/A
Protected

Academic year: 2023

Membagikan "PPT Slide 1"

Copied!
83
0
0

Teks penuh

(1)

Data Structures for Java Data Structures for Java

William H. Ford William H. Ford William R. Topp William R. Topp

Chapter 12 Chapter 12

Iterators Iterators

Bret Ford

© 2005, Prentice Hall

(2)

The Iterator Concept The Iterator Concept

 Many array algorithms are designed Many array algorithms are designed

around a sequential scan of the list using around a sequential scan of the list using

an index.

an index.

 The ArrayList and LinkedList clases The ArrayList and LinkedList clases

implement the List interface and so have implement the List interface and so have

get() and set() methods which access and get() and set() methods which access and

update an element by index.

update an element by index.

(3)

The Iterator Concept The Iterator Concept

(continued) (continued)

 Even though a LinkedList collection has Even though a LinkedList collection has get() and set() methods , the methods get() and set() methods , the methods

have O(n) efficiency and are not suitable have O(n) efficiency and are not suitable

for index-based applications.

for index-based applications.

 The Bag class does not provide any means The Bag class does not provide any means for sequencing through its data.

for sequencing through its data.

(4)

The Iterator Concept The Iterator Concept

(continued) (continued)

 The design of a collection type must The design of a collection type must address the problem of scanning its address the problem of scanning its

elements. There are three guidelines that elements. There are three guidelines that

should apply.

should apply.

(5)

The Iterator Concept The Iterator Concept

(continued) (continued)

 Guideline Guideline 1: A collection must define an 1: A collection must define an efficient scanning mechanism consistent efficient scanning mechanism consistent

with good object-design principles.

with good object-design principles.

Requiring the implementation to make the Requiring the implementation to make the

data public is not a solution. The data public is not a solution. The

mechanism should follow a design pattern mechanism should follow a design pattern

so that general scanning algorithms apply so that general scanning algorithms apply

to all collection types.

to all collection types.

(6)

The Iterator Concept The Iterator Concept

(continued) (continued)

 Guideline 2 Guideline 2 : A collection should provide an : A collection should provide an object, called an

object, called an iterator iterator , that has , that has

methods which allow a scan of a collection methods which allow a scan of a collection

similar to the scan of an array with an similar to the scan of an array with an

index. Methods should allow for a loop to index. Methods should allow for a loop to

sequentially scan the elements.

sequentially scan the elements.

(7)

The Iterator Concept The Iterator Concept

(concluded) (concluded)

 Guideline 3 Guideline 3 : Each collection class : Each collection class

understands its underlying structures and understands its underlying structures and

is thus is responsible for implementing is thus is responsible for implementing

iterator methods.

iterator methods.

(8)

Collection Iterators Collection Iterators

 An iterator is an object that accesses the An iterator is an object that accesses the elements in a collection.

elements in a collection.

 At any point in the scan, the iterator can At any point in the scan, the iterator can access the value of the corresponding

access the value of the corresponding element.

element.

(9)

Collection Iterators (continued) Collection Iterators (continued)

 The figure illustrates an iterator for a The figure illustrates an iterator for a

LinkedList object. In (a) the iterator, called LinkedList object. In (a) the iterator, called

iter, references the first element in the list iter, references the first element in the list

with Integer value 8. In (b), iter has with Integer value 8. In (b), iter has

moved forward one position and moved forward one position and

references Integer value 17.

references Integer value 17.

(10)

Collection Iterators (continued) Collection Iterators (continued)

The generic Iterator interface defines the The generic Iterator interface defines the methods that are available to an iterator.

methods that are available to an iterator.

Every data structure that implements the Every data structure that implements the

Collection interface also implements the Iterator Collection interface also implements the Iterator

interface.

interface.

Creating an iterator is done by the method Creating an iterator is done by the method iterator() which is specified in the Collection iterator() which is specified in the Collection

interface. The method returns an Iterator object interface. The method returns an Iterator object

that references the first element in the collection.

that references the first element in the collection.

(11)

Collection Iterators (concluded) Collection Iterators (concluded)

 Create an iterator by first declaring an Create an iterator by first declaring an Iterator reference variable.

Iterator reference variable.

// declare LinkedList for integer objects LinkedList<Integer> aList;

// declare Iterator for Integer objects Iterator<Integer> iter;

 Call iterator() for the specific collection Call iterator() for the specific collection that you wish to traverse.

that you wish to traverse.

// create iterator and assign to iter iter = aList.iterator();

(12)

Factory Methods Factory Methods

 A factory method is a name for a non- A factory method is a name for a non-

constructor method that creates objects.

constructor method that creates objects.

The method iterator() of a Collection The method iterator() of a Collection

object is a factory method. You use it to object is a factory method. You use it to

create an iterator, not a constructor.

create an iterator, not a constructor.

Iterator<String> iter = aStringList.iterator();

(13)

Iterator Methods Iterator Methods

 The Iterator method hasNext() indicates The Iterator method hasNext() indicates whether more values remain in a

whether more values remain in a collection traversal.

collection traversal.

// continue while there are remaining elements while (iter.hasNext())

{ ... }

(14)

Iterator Methods (continued) Iterator Methods (continued)

 Actual movement through the collection is Actual movement through the collection is done by the method next(), which returns done by the method next(), which returns

the value of the next collection element the value of the next collection element

and moves forward one element.

and moves forward one element.

Calling next() when hasNext() is false results Calling next() when hasNext() is false results in the NoSuchElementException.

in the NoSuchElementException.

(15)

Iterator Methods (continued) Iterator Methods (continued)

 By initializing an iterator and applying a By initializing an iterator and applying a while statement that uses hasNext() and while statement that uses hasNext() and

next(), the following is a template for next(), the following is a template for

scanning a collection.

scanning a collection.

// initialize iter to reference first element in a collection c iter = c.iterator();

// loop accesses successive elements to the end of the collection while (iter.hasNext())

{

// obtain the next value and move forward value = iter.next();

<act on value>

}

(16)

Iterator Methods (concluded) Iterator Methods (concluded)

 The Iterator method remove() is applied The Iterator method remove() is applied after a call to next() and removes the

after a call to next() and removes the collection value returned by next().

collection value returned by next().

(17)

Iterator Interface API

Iterator Interface API

(18)

Generic Iterator Methods Generic Iterator Methods

 Any collection class that implements the Any collection class that implements the Collection interface must include iterators.

Collection interface must include iterators.

 An algorithm that relies on traversing An algorithm that relies on traversing elements in a collection and extracting elements in a collection and extracting

their values can be implemented as a their values can be implemented as a

generic method using an iterator

generic method using an iterator

(19)

max() max()

public static <T extends Comparable<? super T>

T max (Collection c) {

// create an iterator positioned at // the first element

Iterator<T> iter = c.iterator();

// assign maxValue the value of the first // element and advance iter

T maxValue = iter.next(), scanObj;

// scan the rest of the elements in the collection while (iter.hasNext())

{

scanObj = iter.next();

if (scanObj.compareTo(maxValue) > 0) maxValue = scanObj;

}

return maxValue;

}

(20)

Iteration using the Iteration using the

Enhanced for Statement Enhanced for Statement

 When a collection must be accessed When a collection must be accessed

without removing elements, a enhanced without removing elements, a enhanced

form of the for statement can be used. It form of the for statement can be used. It

takes care of sequencing through takes care of sequencing through

collection elements without having to collection elements without having to

declare and use an iterator.

declare and use an iterator.

(21)

Iteration using the Iteration using the

Enhanced for Statement Enhanced for Statement

(concluded) (concluded)

 A collection class must implement the A collection class must implement the

generic interface Iterable in order to use generic interface Iterable in order to use

the enhanced for statement to scan the the enhanced for statement to scan the

elements. The interface does not define elements. The interface does not define

any methods. It simply allows an object to any methods. It simply allows an object to

be used in an enhanced for statement. All be used in an enhanced for statement. All

of the collection classes in this book of the collection classes in this book

implement Iterable.

implement Iterable.

(22)

Enhanced for Statement Enhanced for Statement

Example Example

Time24[] apptArr = {new Time24(8,30), new Time24(10,00), new Time24(12,30), new Time24(1,45), new Time24(3,15)};

LinkedList<Time24> apptList = new LinkedList<Time24>();

// copy elements from array to LinkedList apptList for (int i = 0; i < apptArr.length; i++)

apptList.add(apptArr[i]);

System.out.println("Original appointments: " + apptList);

// enhanced for creates an iterator scan of apptList for (Time24 t : apptList)

t.addTime(120);

System.out.println("Revised appointments: " + apptList);

Output:

Original appointments: [8:30, 10:00, 12:30, 1:45, 3:15]

Revised appointments: [10:30, 12:00, 14:30, 3:45, 5:15]

(23)

List Iterators List Iterators

All List collections have a second type All List collections have a second type

of iterator, called a list iterator that takes of iterator, called a list iterator that takes

advantage of the linear ordering of elements advantage of the linear ordering of elements

in the collection.

in the collection.

A list iterator can traverse the list in either A list iterator can traverse the list in either direction and also modify the list.

direction and also modify the list.

The methods associated with a list iterator The methods associated with a list iterator are specified in the generic ListIterator

are specified in the generic ListIterator

interface which extends the Iterator interface.

interface which extends the Iterator interface.

(24)

List Iterators (continued) List Iterators (continued)

A collection creates a ListIterator object using one A collection creates a ListIterator object using one of two methods.

of two methods.

The List method listIterator() returns a ListIterator The List method listIterator() returns a ListIterator object that references the first element.

object that references the first element.

ListIterator<Integer> lIter = aList.listIterator();

A second version of listIterator() takes a A second version of listIterator() takes a position as an argument and returns a position as an argument and returns a

ListIterator object that references the element ListIterator object that references the element

at the specified position.

at the specified position.

ListIterator<Integer> lIter = aList.listIterator(index);

(25)

List Iterators (continued) List Iterators (continued)

 If index == size(), the iterator points just If index == size(), the iterator points just past the end of the list. This is useful if past the end of the list. This is useful if

we intend to scan the list in the reverse we intend to scan the list in the reverse

direction.

direction.

(26)

List Iterators (continued) List Iterators (continued)

 The ListIterator interface extends the The ListIterator interface extends the Iterator interface and so it defines the Iterator interface and so it defines the

methods hasNext(), next(), and remove().

methods hasNext(), next(), and remove().

 The methods hasPrevious() and previous() The methods hasPrevious() and previous() are available for a backward scan with

are available for a backward scan with

actions that parallel hasNext() and next() actions that parallel hasNext() and next()

in a forward scan.

in a forward scan.

(27)

List Iterators (concluded) List Iterators (concluded)

 An iterator can only remove an element An iterator can only remove an element from a collection. A ListIterator has

from a collection. A ListIterator has

update methods add() and set() that can update methods add() and set() that can

add a new element and assign an element add a new element and assign an element

to have a new value.

to have a new value.

(28)

UML Diagrams for Collection, UML Diagrams for Collection,

List, and their Iterators

List, and their Iterators

(29)

API for Methods Unique to the API for Methods Unique to the

ListIterator Interface

ListIterator Interface

(30)

ListIterator Set Method ListIterator Set Method

The set() method updates the value of The set() method updates the value of an element during an iteration.

an element during an iteration.

The method must be used in tandem with The method must be used in tandem with the methods next() (or previous()) since it the methods next() (or previous()) since it

assigns the new value to the element last assigns the new value to the element last

returned by one of these extraction methods.

returned by one of these extraction methods.

First call next() to extract a value, determine First call next() to extract a value, determine what the update should be, and then use

what the update should be, and then use set() to assign the new updated value.

set() to assign the new updated value.

(31)

ListIterator Set Method ListIterator Set Method

(concluded) (concluded)

8 1 7 3 2

B e f o r e c a l l i n g i t e r . n e x t ( )

i t e r

8 1 2 3 2

A f t e r t h e i n s t r u c t i o n s e q u e n c e i t e r . n e x t ( ) ;

i t e r . s e t ( 1 2 ) ;

i t e r L i s t I t e r a t o r i t e r = a L i s t . l i s t I t e r a t o r ( ) ;

(32)

Backward Scan of a List Backward Scan of a List

 Using the methods hasPrevious() and Using the methods hasPrevious() and

previous(), an iterator can move backward previous(), an iterator can move backward

in a list.

in a list.

The method hasPrevious() returns true if The method hasPrevious() returns true if there are list elements remaining when there are list elements remaining when

traversing the list in the reverse direction.

traversing the list in the reverse direction.

The method previous() returns the previous The method previous() returns the previous element of the list and moves the iterator element of the list and moves the iterator

down one position in the list.

down one position in the list.

(33)

Backward Scan of a List Backward Scan of a List

(concluded)

(concluded)

(34)

Backward Scan of a List Backward Scan of a List

Example Example

 The method reverseOutput() takes a The method reverseOutput() takes a

linked list as an argument and uses a list linked list as an argument and uses a list

iterator to output the list in reverse order.

iterator to output the list in reverse order.

The scan uses the index version of The scan uses the index version of

listIterator() and the methods listIterator() and the methods

hasPrevious() and previous().

hasPrevious() and previous().

(35)

Backward Scan of a List Backward Scan of a List

Example (continued) Example (continued)

public static <T> void reverseOutput(LinkedList<T> aList) {

// create iterator that starts just past the end of the list ListIterator<T> revIter = aList.listIterator(aList.size());

// loop outputs the value of element accessed by previous() while (revIter.hasPrevious())

System.out.print(revIter.previous() + " ");

System.out.println();

}

(36)

Backward Scan of a List Backward Scan of a List

Example (concluded) Example (concluded)

Use reverseOutput() to output colors in the list colorList.

reverseOutput(colorList);

Output:

blue green black red

(37)

ListIterator Add Method ListIterator Add Method

 The list iterator add() method inserts a The list iterator add() method inserts a new element into the list immediately new element into the list immediately

before the value that would be returned before the value that would be returned

by next() and after the previous list value.

by next() and after the previous list value.

listIter.add(5);

(38)

ListIterator Add Method ListIterator Add Method

(continued) (continued)

After inserting the element, the iterator still After inserting the element, the iterator still references the same element. However, a references the same element. However, a call to previous() will return the new value.

call to previous() will return the new value.

If the iterator references the first element If the iterator references the first element (hasPrevious() == false), add() inserts a (hasPrevious() == false), add() inserts a

new element at the front of the list.

new element at the front of the list.

If the iterator points past the end of the list, If the iterator points past the end of the list, then add() inserts a new element at the back then add() inserts a new element at the back

of the list.

of the list.

(39)

ListIterator Add Method ListIterator Add Method

(concluded)

(concluded)

(40)

ListIterator Add Method ListIterator Add Method

Example Example

The method insertList() takes two LinkedList The method insertList() takes two LinkedList

arguments aList and bList along with an integer arguments aList and bList along with an integer argument pos specifying a position in aList. The argument pos specifying a position in aList. The

method inserts elements from bList into aList method inserts elements from bList into aList

starting at index pos. Two list iterators are starting at index pos. Two list iterators are

used. The first uses listIterator(pos) to create used. The first uses listIterator(pos) to create

an iterator in aList at the specified index and an iterator in aList at the specified index and

the second uses listIterator() to create an the second uses listIterator() to create an

iterator at the first element in bList .

iterator at the first element in bList .

(41)

ListIterator Add Method ListIterator Add Method

Example (continued) Example (continued)

public static <T>void insertList(LinkedList<T> aList, LinkedList<T> bList, int pos) {

// declare iterator and set to start of the list ListIterator<T> aIter = aList.listIterator(pos), bIter = bList.listIterator();

// scan bList and insert (add) elements into aList; iterator // aIter continues to reference the same element

while (bIter.hasNext())

aIter.add(bIter.next());

}

(42)

ListIterator Add Method ListIterator Add Method

Example (concluded) Example (concluded)

Assume stateListA and stateListB are two LinkedList collections Assume stateListA and stateListB are two LinkedList collections containing string abbreviations for US states. The statements containing string abbreviations for US states. The statements insert stateListB into stateListA at position 2 and then display insert stateListB into stateListA at position 2 and then display the updated list.

the updated list.

aList: {"NY", "AL", "MT", "MA"} bList: {"WI", "TN", "NV"}

insertList(stateListA, stateListB, 2);

System.out.println(stateListA);

Output: [NY, AL, WI, TN, NV, MT, MA]

(43)

The Iterator Design Pattern The Iterator Design Pattern

 The iterator design pattern provides a The iterator design pattern provides a means accessing the elements of a

means accessing the elements of a

collection in order from first to last with no collection in order from first to last with no

concern for the underlying implementation concern for the underlying implementation

of the collection.

of the collection.

This is precisely what Iterator provides in a This is precisely what Iterator provides in a general collection.

general collection.

A ListIterator provides additional functionality A ListIterator provides additional functionality related to the sequential storage of data.

related to the sequential storage of data.

(44)

Ordered Lists Ordered Lists

 Many applications require an ordered Many applications require an ordered list. Adding a new element requires list. Adding a new element requires

scanning existing values and identifying scanning existing values and identifying the correct location at which to add the the correct location at which to add the

new element.

new element.

Begin by initializing a list iterator to reference Begin by initializing a list iterator to reference the start of the list.

the start of the list.

Scan the list, looking for the first element Scan the list, looking for the first element whose value is

whose value is ≥ ≥ the new item. the new item.

This identifies the insertion location. Use the This identifies the insertion location. Use the add() method to place the new item in the list.

add() method to place the new item in the list.

(45)

Ordered Lists (continued) Ordered Lists (continued)

 Assume intList is a linked list containing Assume intList is a linked list containing the Integer values 60, 65, 74, and 82 and the Integer values 60, 65, 74, and 82 and

curr is the list iterator.

curr is the list iterator.

(46)

Ordered Lists (continued) Ordered Lists (continued)

 Insert 50 in the list: Insert 50 in the list:

A first call to next() extracts the value 60, A first call to next() extracts the value 60, which is

which is ≥ ≥ 50, and the scan terminates with 50, and the scan terminates with curr referencing the second element in the curr referencing the second element in the

list.

list.

Value 50 should be added to the front at the Value 50 should be added to the front at the element curr originally referenced before it element curr originally referenced before it

advanced to 65. Move the iterator backward advanced to 65. Move the iterator backward

with previous() and use add().

with previous() and use add().

(47)

Ordered Lists (continued) Ordered Lists (continued)

 Insert 70 in the list: Insert 70 in the list:

The scan terminates when next() extracts the The scan terminates when next() extracts the value 74 which is the first value that is

value 74 which is the first value that is ≥ ≥ 70. 70.

As in the first case, use previous() to reset As in the first case, use previous() to reset

curr and then use add() to insert the element.

curr and then use add() to insert the element.

(48)

Ordered Lists (concluded) Ordered Lists (concluded)

 Insert 90 in the list: Insert 90 in the list:

The scan of the list fails to find an element The scan of the list fails to find an element with greater than 90. The iterator curr has with greater than 90. The iterator curr has

reached the end of the list reached the end of the list

(curr.hasNext() == false). Insert 90 at the (curr.hasNext() == false). Insert 90 at the

back of the list referenced by the current back of the list referenced by the current

value of curr.

value of curr.

c u r r . a d d ( 9 0 ) i n s e r t s 9 0 8 2 9 0

7 4

6 0 6 5

c u r r c u r r i s p o s i t i o n e d a t t h e e n d o f t h e l i s t

8 2 7 4

6 0 6 5

c u r r

(49)

insertOrder() insertOrder()

// insert item into the ordered list

public static <T extends Comparable<? super T>>

void insertOrder(LinkedList<T> orderedList, T item) {

// curr starts at first list element

ListIterator<T> curr = orderedList.listIterator();

// move forward until encountering the end // of the list or locating the insertion // point inside the list

while (curr.hasNext())

// check if item is <= value extracted by next() if(item.compareTo(curr.next()) <= 0)

{

// if so, reset curr back one // position and exit loop

curr.previous();

break;

}

(50)

insertOrder() (continued) insertOrder() (continued)

// add item before curr; if curr is // at the end of the list adds item // as the last element of the list curr.add(item);

}

(51)

insertOrder() (concluded) insertOrder() (concluded)

If the list has n elements, the If the list has n elements, the

worst-case performance occurs when the worst-case performance occurs when the

insertion occurs at the end of the list. This case insertion occurs at the end of the list. This case

requires n comparisons and has running time requires n comparisons and has running time O(n) O(n)

On the average, we expect to search half the list On the average, we expect to search half the list to find an insertion point. As a result, the

to find an insertion point. As a result, the average running time is O(n).

average running time is O(n).

The best case is O(1), which occurs when the The best case is O(1), which occurs when the insertion takes place at the front of the list.

insertion takes place at the front of the list.

(52)

Removing Duplicates from an Removing Duplicates from an

Ordered List Ordered List

 The process involves scanning the list with The process involves scanning the list with an iterator and comparing the current

an iterator and comparing the current

value with a target value. The algorithm is value with a target value. The algorithm is

presented using an example.

presented using an example.

(53)

Removing Duplicates from an Removing Duplicates from an

Ordered List (continued) Ordered List (continued)

 In the figure, the iterator curr initially In the figure, the iterator curr initially

references the first element in the list. A references the first element in the list. A

call to next() extracts the value 5 and call to next() extracts the value 5 and

moves the iterator. The initial value moves the iterator. The initial value

becomes the target value.

becomes the target value.

(54)

Removing Duplicates from an Removing Duplicates from an

Ordered List (continued) Ordered List (continued)

 A second call to next() extracts a duplicate A second call to next() extracts a duplicate value which is removed from the list. Note value which is removed from the list. Note

that curr now references 7 and the that curr now references 7 and the

deletion removes the previous element.

deletion removes the previous element.

(55)

Removing Duplicates from an Removing Duplicates from an

Ordered List (continued) Ordered List (continued)

 Two additional calls to next() extract Two additional calls to next() extract

values that are not duplicates. Each value values that are not duplicates. Each value

updates the target (figure (a) (b)). ‑

updates the target (figure (a) (b)). ‑

(56)

Removing Duplicates from an Removing Duplicates from an

Ordered List (concluded) Ordered List (concluded)

A final call to next() extracts a duplicate A final call to next() extracts a duplicate

value and moves curr past the end of the list.

value and moves curr past the end of the list.

The duplicate element is removed and the The duplicate element is removed and the

scan results in an ordered list without scan results in an ordered list without

duplicate values.

duplicate values.

5 7 8 8

c u r r V a l u e = c u r r . n e x t ( ) = 8

D e l e t e 8 ( c u r r . r e m o v e ( ) )

(57)

removeDuplicates removeDuplicates

// remove duplicate values from the linked list public static <T> void removeDuplicates(

LinkedList<T> aList) {

// current value and the target T currValue, target;

// list iterator that scans the list Iterator<T> curr;

// start at the front of the list curr = aList.iterator();

// assign target the first list element // and move to the second element

target = curr.next();

(58)

removeDuplicates removeDuplicates

(concluded) (concluded)

// cycle through the list and remove duplicates while(curr.hasNext())

{

// record the current list value currValue = curr.next();

// if currValue equals target, remove it;

// otherwise reassign the target to the // current value

if (currValue.equals(target)) curr.remove();

else

target = currValue;

} }

(59)

OrderedList Collection OrderedList Collection

 Use inheritance to create an ordered list Use inheritance to create an ordered list class by extending the LinkedList class.

class by extending the LinkedList class.

The subclass can use the Collection interface The subclass can use the Collection interface methods in the superclass and can also use the methods in the superclass and can also use the

indexed-based remove() and get() methods in indexed-based remove() and get() methods in

LinkedList. These methods do not affect the LinkedList. These methods do not affect the

ordering of the elements.

ordering of the elements.

List update methods such as add() and set() List update methods such as add() and set() and ListIterator methods add() and set() can and ListIterator methods add() and set() can

destroy the ordering of the list.

destroy the ordering of the list.

(60)

OrderedList Collection OrderedList Collection

(concluded) (concluded)

 Let the LinkedList superclass store the Let the LinkedList superclass store the elements.

elements.

Override the add() method that inserts an Override the add() method that inserts an element at the back of the list using the element at the back of the list using the

implementation of the insertOrder() algorithm.

implementation of the insertOrder() algorithm.

Invalidate the inappropriate methods Invalidate the inappropriate methods

add(index, element), addFirst(), addLast(), add(index, element), addFirst(), addLast(),

and set() by overriding them with code that and set() by overriding them with code that

throws an exception.

throws an exception.

(61)

OrderedList Class Methods OrderedList Class Methods

 The OrderedList class has a constructor The OrderedList class has a constructor that creates an empty list. Its

that creates an empty list. Its

implementation simply calls the default implementation simply calls the default

constructor in the superclass.

constructor in the superclass.

// constructor creates an empty ordered list public OrderedList()

{ super(); }

(62)

OrderedList Class Methods OrderedList Class Methods

(continued) (continued)

 All of the LinkedList methods that could All of the LinkedList methods that could destroy the ordering of elements in a

destroy the ordering of elements in a collection are overridden with an

collection are overridden with an implementation that throws an implementation that throws an

UnsupportedOperationException.

UnsupportedOperationException.

// insert element at an index:

public void add(int index, T item) {

throw new UnsupportedOperationException

("OrderedList add(index, element): Invalid operation");

}

(63)

OrderedList Class Methods OrderedList Class Methods

(concluded) (concluded)

 The implementation of add() uses the The implementation of add() uses the algorithm for insertOrder() with a final algorithm for insertOrder() with a final

statement that returns the boolean value statement that returns the boolean value

true indicating that a new element enters true indicating that a new element enters

the list.

the list.

public boolean add(T item) {

< code for insertOrder() >

return true;

}

(64)

OrderedList Class Example OrderedList Class Example

// create an empty list and a list iterator reference OrderedList<String> ordList = new OrderedList<String>();

Iterator<String> iter;

ordList.add("green"); // List: green

ordList.add("blue"); // List: blue green ordList.add("red"); // List: blue green red

ordList.add("black"); // List: black blue green red index = ordList.indexOf("red"); // index = 3

ordList.remove(2); // List: black blue red // initialize iter to reference the first element

iter = ordList.iterator();

// output value from next()

Sytem.out.println(iter.next()); // Output: black // move the iterator, delete element and output list iter.next();

iter.remove(); // delete blue

System.out.println(ordList);

Output: [black, red]

(65)

Application - Word Frequencies Application - Word Frequencies

 A document is input from a text file and A document is input from a text file and output displays the distinct words and output displays the distinct words and

their frequencies in alphabetical order.

their frequencies in alphabetical order.

The application uses the class WordFreq The application uses the class WordFreq

whose instances store a word and the whose instances store a word and the

number of times the word has occurred number of times the word has occurred

(the word frequency).

(the word frequency).

(66)

Application - Word Frequencies Application - Word Frequencies

(continued) (continued)

 When a word is first encountered in the When a word is first encountered in the document, the WordFreq constructor

document, the WordFreq constructor creates an object with the word and a creates an object with the word and a

frequency of 1.

frequency of 1.

 For each subsequent occurrence of the For each subsequent occurrence of the word, use the method increment() which word, use the method increment() which

increments the frequency field in the increments the frequency field in the

object.

object.

(67)

Application - Word Frequencies Application - Word Frequencies

(continued) (continued)

 In order that its objects can be stored in In order that its objects can be stored in an OrderedList collection, the WordFreq an OrderedList collection, the WordFreq

class implements equals() and class implements equals() and

compareTo(). These methods use the compareTo(). These methods use the

word field to compare objects.

word field to compare objects.

(68)

Application - Word Frequencies Application - Word Frequencies

(continued) (continued)

Declare the OrderedList collection wordList Declare the OrderedList collection wordList and a Scanner that is linked to a user

and a Scanner that is linked to a user designated text file.

designated text file.

A while loop processes each word from the file. A while loop processes each word from the file.

After reading a word, use the constructor to create a After reading a word, use the constructor to create a WordFreq object wf with the word as its argument.

WordFreq object wf with the word as its argument.

The method search()looks for a target in an The method search()looks for a target in an

OrderedList and returns an iterator referencing the OrderedList and returns an iterator referencing the

value or null if the target is not in the list.

value or null if the target is not in the list.

(69)

Application - Word Frequencies Application - Word Frequencies

(concluded) (concluded)

 In the figure, a search for "pickled" uses In the figure, a search for "pickled" uses the WordFreq object wf = <"pickled",1>.

the WordFreq object wf = <"pickled",1>.

The return value is an iterator denoted by The return value is an iterator denoted by

iter. The frequency for the object iter. The frequency for the object

<"pickled",3> is incremented so the

<"pickled",3> is incremented so the frequency is 4.

frequency is 4.

(70)

search() search()

public static <T extends Comparable<? super T>>

ListIterator<T> search(OrderedList<T>

ordList, T target) {

// initialize a list iterator

ListIterator<T> iter = ordList.listIterator();

T curr;

// move through the ordered list while (iter.hasNext())

{

// get the current list value curr = iter.next();

(71)

search() (concluded) search() (concluded)

// see if current value matches target if (curr.equals(target))

{

// match; move iterator back to the match // and return its value

iter.previous();

return iter;

}

// if the target is less than current // value, we won't find the target in // the ordered list

else if (target.compareTo(curr) < 0) return null;

}

// the target is larger than any value in the list return null;

}

(72)

Program 12.1 Program 12.1

import ds.util.OrderedList;

import ds.util.ListIterator;

import java.util.Scanner; // for file input import java.io.*;

public class Program12_1 {

public static void main(String[] args) throws IOException

{

// words read from file and inserted // into wordList

OrderedList<WordFreq> wordList = new OrderedList<WordFreq>();

// scanner to parse words in the file Scanner fileIn;

(73)

Program 12.1 (continued) Program 12.1 (continued)

// strings for input line and parse // of words on the line

String word = null;

// WordFreq object for elements in wordList WordFreq wf = null;

// use to search for the current word // in the ordered list

ListIterator<WordFreq> iter;

// scanner name is a command-line argument

fileIn = new Scanner (new FileReader(args[0]));

(74)

Program 12.1 (continued) Program 12.1 (continued)

// input words to end-of-file while (fileIn.hasNext())

{

word = fileIn.next();

// create a wordFreq object with frequency 1 wf = new WordFreq(word);

// search to see if object is in the list iter = search(wordList, wf);

if (iter != null)

// yes; increment the word frequency iter.next().increment();

else

// word is new; insert obj into the list wordList.add(wf);

}

displayWords(wordList);

(75)

Program 12.1 (continued) Program 12.1 (continued)

public static <T extends Comparable<? super T>>

ListIterator<T> search(OrderedList<T> ordList, T target)

{

// initialize a list iterator

ListIterator<T> iter = ordList.listIterator();

T curr;

// move through the ordered list while (iter.hasNext())

{

// get the current list value curr = iter.next();

(76)

Program 12.1 (continued) Program 12.1 (continued)

// see if current value matches target if (curr.equals(target))

{

// match; move iterator back to the match // and return its value

iter.previous();

return iter;

}

// if the target is less than current

// value, we would not find the target in // the ordered list

else if (target.compareTo(curr) < 0) return null;

}

// the target is larger than any value // in the list

return null;

}

(77)

Program 12.1 (continued) Program 12.1 (continued)

// output the word and frequency in 15 // character positions; limit output to 4 // elements per line

public static void displayWords(OrderedList aList) {

ListIterator iter = aList.listIterator();

int count = 0, i;

String blanks;

(78)

Program 12.1 (concluded) Program 12.1 (concluded)

while (iter.hasNext()) {

String str = iter.next().toString();

System.out.print(str);

blanks = "";

for (i=0;i < 15-str.length();i++) blanks += " ";

System.out.print(blanks);

count++;

if (count % 4 == 0)

System.out.println();

}

System.out.println();

} }

(79)

Program 12.1 (Run) Program 12.1 (Run)

File "wf.dat":

peter piper picked a peck of pickled peppers a peck of pickled peppers peter piper picked if peter piper picked a peck of pickled peppers where is the peck that peter piper picked

Run:

a (3) if (1) is (1) of (3)

peck (4) peppers (3) peter (4) picked (4) pickled (3) piper (4) that (1) the (1) where (1)

(80)

The Adapter Design Pattern The Adapter Design Pattern

The The adapter design pattern adapter design pattern converts converts

the public portion (interface) of a class into another the public portion (interface) of a class into another interface.

interface.

You use the adapter pattern when you want to use an You use the adapter pattern when you want to use an

existing class whose interface does not match the one you existing class whose interface does not match the one you need.

need.

The OrderedList subclass with its revised add() method is an The OrderedList subclass with its revised add() method is an application of the adapter pattern.

application of the adapter pattern.

In addition to inheritance, object composition can also be In addition to inheritance, object composition can also be used to realize the adapter pattern. The stack and queue used to realize the adapter pattern. The stack and queue classes in Chapters 14 and 15 are built using this

classes in Chapters 14 and 15 are built using this technique.

technique.

(81)

Selecting a Sequence Collection Selecting a Sequence Collection

 Use a Java array only for problems where Use a Java array only for problems where you know the number of data items in

you know the number of data items in advance. Because an ArrayList also

advance. Because an ArrayList also

provides direct access using its get() and provides direct access using its get() and

set() methods and has the ability to grow set() methods and has the ability to grow

to meet the demands of the application, it to meet the demands of the application, it

is often advisable to use an ArrayList is often advisable to use an ArrayList

instead of an array.

instead of an array.

(82)

Selecting a Sequence Collection Selecting a Sequence Collection

(continued) (continued)

 Use an ArrayList if the application needs Use an ArrayList if the application needs

direct access and the program performs all direct access and the program performs all

insertions and deletions at the end of the insertions and deletions at the end of the

sequence. If the application requires sequence. If the application requires

infrequent modifications to the sequence infrequent modifications to the sequence at intermediate positions, an ArrayList is at intermediate positions, an ArrayList is

still acceptable. However, applications still acceptable. However, applications

requiring frequent insert and delete requiring frequent insert and delete

operations at intermediate locations should operations at intermediate locations should

use a LinkedList collection

use a LinkedList collection

(83)

Selecting a Sequence Collection Selecting a Sequence Collection

(concluded) (concluded)

Use a LinkedList when the application Use a LinkedList when the application

requires frequent insertions and deletions at requires frequent insertions and deletions at

arbitrary locations in the list and direct arbitrary locations in the list and direct

(index) access is not required. A LinkedList is (index) access is not required. A LinkedList is

not a good choice if the application requires not a good choice if the application requires many search operations. These applications many search operations. These applications

should use a set or map. These collections should use a set or map. These collections

provide very fast running times for searches.

provide very fast running times for searches.

Sets and maps are discussed in Chapter 19.

Sets and maps are discussed in Chapter 19.

Referensi

Dokumen terkait

This study was intended to investigate students’ attitudes toward learning English of Islamic Junior School that divided into three categories: behavior,

knowledge building&#34;, International Journal of Computer-Supported Collaborative Learning, 2022