chapter 11 array-based lists. 2 knowledge goals understand the list abstraction and basic list...

61
Chapter 11 Array-Based Lists

Upload: lexi-garness

Post on 30-Mar-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

Chapter 11Array-Based Lists

Page 2: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

2

Knowledge Goals• Understand the list abstraction and basic list

operations• Recognize the difference between an array and a

list• Understand how to use an array to represent a

list• Know how to use a key to establish the order of a

sorted list• Understand the principle of "divide and conquer"

as expressed in the binary search algorithm

Page 3: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

3

Skill Goals

• Add an item to a list• Remove an item from a list• Search for an item in a list• Sort the items in a list into ascending or

descending order• Build a list in sorted order• Search for an item in a sorted list using a

linear search

Page 4: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

4

Skill Goals

• Search for an item using a binary search• Define a class that extends a Java

interface• Use Java's Comparable interface• Use ArrayList from the Java library

Page 5: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

5

What is a List?

List

A homogeneous collection of elements, with a linear relationship between the elements

Linear relationship

Every element (except the first) has a unique predecessor, and every element (except the last) has a unique successor

Length (size in Java)

The number of items in a list; it can vary over time

Page 6: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

6

What is a List?

Sorted list: The predecessor and successor relation-ships are determined by the content of the keys

Key

Key

Page 7: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

7

What is a List?

We are concerned only with unique keys

Page 8: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

8

A List Class

Can you name some of the operations that must be applied to a List?

Page 9: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

9

A List Class

Page 10: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

10

A List Class

Transformers add remove

Observers isEmpty isFull size contains hasNext

Iterators resetList next

change state

observe state

process components

Page 11: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

11

A List Class

Attributes

numItems

listItems[0]

. . .

listItems[listItems.length-1]

currentPos

number of elements in list

array of list elements

used by iterator

Page 12: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

12

A List Class

Page 13: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

13

A List Class

UNSORTED LIST

Elements are placed into the list in no particular order with respect to their content

SORTED LIST

List elements are in an order that is sorted by the content of their keys -- either numerically or alphabetically

Class ListOfStrings is unsorted

Page 14: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

14

A List Class

public ListOfStrings() { numItems = 0; listItems = new String[100]; currentPos = 0;}

public ListOfStrings(int maxItems) { numItems = 0; listItems = new String[maxItems]; currentPos = 0;}

constructors

Page 15: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

15

A List Class

public boolean isEmpty()

{

return (numItems == 0)

}

public int size()

{

return numItems;

}

public boolean isFull()

{

return (numItems == listItems.length);

}

observers

Page 16: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

16

A List Classpublic boolean contains(String item)

{

int index = 0;

while (index < numItems &&

listItems[index].compareTo(item) != 0)

index++;

return (index < numItems);

}

See why this works?

Page 17: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

17

Add: Does it matter where we put the item?

numItems 3

listItems [ 0 ] 15

[ 1 ] 39

[ 2 ] -90

[ 3 ] .

. . [ listItems.length-1 ]

Place the itemin numItems location and increment numItems

item 63

Page 18: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

18

After Inserting 64 into an Unsorted List

numItems 4

listItems [ 0 ] 15

[ 1 ] 39

[ 2 ] -90

[ 3 ] 64 .

. . [ listItems.length-1 ] item 64

Page 19: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

19

public void add(String item)// Result: If the list is not full, puts item as// the last position in the list; otherwise list// is unchanged{ if (!isFull()) {

listItems[numItems] = item;

numItems++; }}

A List Class

Page 20: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

20

A List class

remove(item)

Search (item, found, index)

if (found)

Shift remainder of list up

Decrement numItems

Remove is more difficult

ShiftUp

for count going from index downTo numItems

Set listItems[count] to listItems[count+1]

Page 21: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

21

Can you walk through deleting 39?

numItems 4

listItems [ 0 ] 15

[ 1 ] 39

[ 2 ] -90

[ 3 ] 64 .

. . [ listItems.length-1 ]

Page 22: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

22

public void remove(String item) { int index = 0; boolean found = false; while (index < numItems && !found) { if (listItems[index].compareTo(item) == 0) found = true; else index++; } if (found) { for (int count = index; count < numItems - 1; count++)

listItems[count] = listItems[count + 1];

numItems--; }}

The List Class

Page 23: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

23

public void resetList() { currentPos = 0; } public boolean hasNext() { return (currentPos != numItems); }

public String next()// Returns the item at the currentPos position// Assumptions: No transformers are called during the // iteration

A List Class

{

String next = listItems[currentPos]; currentPos++; return next;}

Readdocumentation

carefully!

Page 24: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

24

A List Class

How areCRC cardsand UMLdiagrams

alike?How are

theydifferent?

Page 25: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

25

A List Class

A class is not complete until

it has been tested!

Command-driven test driver

A driver program that reads in commands and executes them; an excellent vehicle for unit testing a class

enum Operations {ADD, REMOVE, SIZE, ISEMPTY, ISFULL, CONTAINS, PRINT, QUIT}

Page 26: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

26

A List Class

Main

Read file into list

Set operation to inOperation()

Set keepGoing to true

while (keepGoing)

Execute operation

Set operation to inOperation

Write list to file

Acommand-

driventesting

program

Page 27: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

27

A List Class

executeOperation

switch(operation)

case ADD: // execute add

case REMOVE: // execute remove

case SIZE: // execute size

case ISEMPTY: // execute isEmpty

case ISFULL: // execute isFull

case CONAINS: // execute contains

case PRINT: // print list

case QUIT: // quit

How areresetList,hasNext,and next

tested?

Page 28: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

28

ListWithSort

Sorting

Arranging the components of a list into order

Page 29: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

29

ListWithSort

Straight selection sort Examine the entire list to select the smallest element Swap that element with first element (with array index 0) Examine the remaining list to select the smallest

element from it Swap that element with second element (array index 1) Continue process until only 2 items remain Examine the last 2 remaining list elements to select the

smallest one Swap that element with the other

Page 30: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

30

ListWithSort

Page 31: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

31

ListWithSort

Canyou use

the sametest

driver?

Page 32: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

32

A Sorted List

Is ListWithSort the same as a SortedList?

Are the same operations needed for a List and a SortedList? Any extra ones needed?

From the client's (user's) point of view, what is the visible difference between an unsorted list and a sorted list?

Page 33: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

33

Page 34: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

34

A Sorted List

Page 35: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

35

A Sorted List

Add

Page 36: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

36

public void add(String item){ if (! isFull()) {// find proper location for new element

int index = numItems - 1;

while (index >= 0 &&

item.compareTo(listItems[index]) < 0) { listItems[index + 1] = listItems[index]; index--; } listItems[index +1] = item; // insert item numItems++; }}

A Sorted List

Page 37: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

37

A Sorted List

remove andnextmust

maintainorder

but theyalready

do!

Page 38: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

38

Searching

Linear (sequential) search

Search begins at the beginning of the list and continues until the item is found or the entire list has been searched

Can searching be improved if the items are in sorted order?

Page 39: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

39

Searching

3 34 7 99 66 11

[0] [1] [2] [3] [4] [5]

How many comparisons are needed to find 11? 67? 2? 100?

3 7 11 34 66 99

[0] [1] [2] [3] [4] [5]

How many comparisons are needed to find 11? 67? 2? 100?

That's better, but we can do better yet

Page 40: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

40

Searching

Binary search (list must be sorted)Search begins at the middle and finds the item or eliminates half of the unexamined items; process is repeated on the half where the item might be

Say that again…

Page 41: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

41

Searching

Page 42: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

42

Searching

Boolean Binary Search (first, last)If (first > last)

return falseElse

Set middle to (first + last)/2Set result to item.compareTo(list[middle])If (result is equal to 0)

return trueElse

If (result < 0)Binary Search (first, middle - 1)

ElseBinary Search (middle + 1, last)

Page 43: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

43

Searching

Searching for "bat"

Page 44: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

44

Searching

Page 45: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

45

public boolean isThere(String item) // Assumption: List items are in ascending order// Returns true if item is in the list; false otherwise{ int first = 0; int last = numItems - 1; int middle; boolean found = false; while (last >= first && !found) { middle = (first + last) / 2; if (item.compareTo(listItems[middle]) == 0) found = true; // Item has been found else if (item.compareTo(listItems[middle] < 0) last = middle - 1; // Look in first half else first = middle + 1; // Look in second half } return found;}

Searching

Page 46: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

46

Searching

Is a binary searchalways better?

Length Sequential Binary

10 5.5 2.9

100 50.5 5.8

1,000 500.5 9.0

10,000 5000.5 12.0

Average Number of iterations

Page 47: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

47

Refactoring the List Hierarchy

Refactoring

Modifying code to improve its quality without changing is functionality

Thereisa

betterway!

Page 48: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

48

Refactoring the List Hierarchy

public abstract class AbstractList{ public AbstractList() public AbstractList(int maxItems) public boolean isFull() public boolean isEmpty() public int size() public void resetList() public boolean hasNext() public String next() public boolean contains(String item) public abstract void remove(String item) public abstract void add(String item)}

What about contains?

Page 49: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

49

Refactoring the List Hierarchy

Page 50: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

50

List of Comparable Objects

Wouldn't it be nice if we could have one abstract class for any data type, not one for each type of item that could be on the list?

You can if you declare the type of the items to be Comparable

protected Comparable[] listItems

Page 51: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

51

List of Comparable Objects

public abstract class AbstractList{ public AbstractList() public AbstractList(int maxItems) public boolean isFull() public boolean isEmpty() public int size() public void resetList() public boolean hasNext() public String next() public boolean contains(Comparable item) public abstract void remove(Comparable item) public abstract void add(Comparable item)}

Page 52: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

52

List of Comparable Objectspublic AbstractList(){ numItems = 0; listItems = new Comparable[100]; currentPos = 0;}

public void add(Comparable item){ if (!isFull()) { listItems[numItems] = (String) item; numItems++; }}

Abstract class

Derived class

Page 53: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

53

Preview of Java Collections

Java Collections

A collection of interfaces, abstract classes, and classes available in java.util that describe data structures available for you to use

Why do you think we covered array-based listsbefore mentioning the Java Collections?

Page 54: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

54

Preview of Java CollectionsArrayList<type>(int number)

Returns an array with an initial capacity of number elements.

add(Object anObject) anObject is appended to the end of the list

size() Returns the number of elements

remove(Oject anObject)

Removes an instance of anObject if it is there

isEmpty Returns true of the list contains no elements

contains(Object,

anObject)

Returns true if anObject is in the list

iterator() Returns an Iterator over the elements of the list

Plus lots more that are different

Page 55: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

55

Preview of Java Collections

import java.util.*;import java.io.*;public class ListDriver{ private static Scanner inFile; private static PrintWriter outFile; public static void main(String[] args) throws

IOException { inFile = new Scanner(new FileReader("list.dat")); outFile = new PrintWriter(new FileWriter("list.out")); ArrayList list = new ArrayList(4); String line;

different

Page 56: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

56

while (inFile.hasNextLine()) { line = inFile.nextLine(); list.add(line); }

// Declare and instantiate iteratorIterator iterator = list.iterator(); while (iterator.hasNext()) System.out.println(iterator.next());

inFile.close(); outFile.close(); }}

Preview of Java Collections

differentlook

closely

Page 57: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

57

Extras - GUI Track

Page 58: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

58

Extras - GUI Track

Handling events from multiple sources with panels requires

declaring and instantiating a JPanel object setting the layout manager for the panel doing everything necessary to create a

button adding the button to the panel declaring and instantiating multiple objects

of the class with the panel

Page 59: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

59

Extras - GUI Track

Threeinstancesof class

containingpanel

Page 60: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

60

Extras - GUI Track

Handling events from multiple sources with the same listener requires

doing everything necessary to create multiple buttons

handler gets a button's name from actionPerformed parameter

handler uses if statement to determine which button was pressed

Page 61: Chapter 11 Array-Based Lists. 2 Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and

61

Extras - GUI Track

Windowwiththree

buttonsand onelistener