Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between...

78
Chapter 12 Data Structures and Collections
  • date post

    20-Jan-2016
  • Category

    Documents

  • view

    219
  • download

    0

Transcript of Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between...

Page 1: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

Chapter 12

Data Structures

and Collections

Page 2: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

2

Knowledge Goals

• Understand the difference between array and linked implementations of a list

• Know how to a stack works• Know how a queue works• Know how a binary tree works• Know how a hash table works• Understand the concepts behind the java

collections framework

Page 3: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

3

Skill Goals

• Develop a linked data structure• Use the ArrayList and LinkedList classes• Use the HashSet and TreeSet classes• Use the Stack class• Use the LinkedList class to implement a

queue• Choose when to use an array-based versus a

linked implementation of a data structure

Page 4: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

4

Linked Structures

Array-basedlist isfixedsize

Page 5: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

5

Linked Structures

Array-based is

physicallyordered;linked islogicallyordered,

whichmeans …

Page 6: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

6

Linked Structures

Insertionsand

deletionsare

easier

Page 7: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

7

Linked Structure

Linked list

A list in which the order of the components is determined by an explicit link field in each node, rather than by the sequential order of the components in memory

External reference (pointer)

A named variable that references (points to) the first node (head) of a linked list

Yes, but how does it work?

Page 8: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

8

Linked StructureList

A node

Each node containsitem and a link

External pointer

Page 9: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

9

Linked Structures

class Node

{

Node link = null;

String item;

Node()

{ item = ""; }

Node(String data)

{ item = data; }

}

null is a keywordmeaning points to

nothing

defaultconstructor

parameterizedconstructor

Page 10: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

10

Linked Structures

Let's create a linked list with three nodes, containing "Adams", "Baker", and "Carter"

We begin by creating two variables

Node current; // Pointer used to keep track // of where we

are in the list

Node list; // External point to the list

Result

Page 11: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

11

Linked Structures

list = new Node("Adams");

current = list;

Result

Page 12: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

12

Linked Structures

current.link = new Node("Baker");

Result

Page 13: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

13

Linked Structures

current = current.link;

Result

Page 14: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

14

Linked Structures

current.link = new Node("Carter");

current = current.link;

Result

Page 15: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

15

Linked Structures

Traversal

Visiting every node in a data structure following an organized pattern of access

current = list; while (current.link != null){ System.out.println(current.item); current = current.link; }

What is the pattern of access?

Page 16: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

16

Linked Structures

Which of thesewill change

with thelinked

version?

Page 17: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

17

Linked Structures

Does the CRC cardfor a class change

with the implementation?

Page 18: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

18

Linked Structures

Observer operations

public boolean isEmtpy()

{ return list == null; }

public boolean contains(String item)

{

Node current = list;

while (current != null &&

curent.item.compareTo(item) != 0)

curent = current.link;

return current != null

}

Page 19: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

19

Linked Structures

if (list.contains("Doggett"))…

Searchwhenitemis notin the

list

Page 20: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

20

Linked Structures

Size in an array-based list just returns numItems; What about in a linked-implementation?

– Can keep a counterincrement with each insertion

decrement with each deletion

– Can count the number of items each time

Which is best (better)?

Page 21: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

21

Linked Structures

public int size(){ Node current = list; int numItems = 0; while (current != null) { numItems++; current = current.link; } return numItems;}

Is this anexample

of atraversal?

Page 22: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

22

Linked Structures

MutatorsAdd– Insert where? To match array-based traversal, new

item must go at the end– How to find end? Search or keep a pointer– Special case(s)? Empty list

tail

Page 23: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

23

Linked Structure

public void add(String newItem) { Node item = new Node(newItem); if (list == null) { list = item; tail = item; } else { tail.link = item; tail = tail.link; }}

Empty listSet list and tail

to item

Not empty listSet item as last nodeSet tail to last node

Page 24: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

24

Linked Structures

Remove– Item not there? Do nothing– What if item is the first? Reset external pointer– What if item is the last? Reset tail pointer– What if item is anywhere else? General case

Page 25: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

25

Linked Structures

Can't be reached;System recaptures it

Page 26: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

26

Linked Structures

What is prior?

Remove "Adams"

Page 27: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

27

Linked StructuresRemove "Carter"

Page 28: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

28

Linked Structures

Remove "Adams" (only node)

Page 29: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

29

public void remove(String item) { Node current = list; Node prior = null; while (current != null && current.item.compareTo(item) != 0)

{ prior = current; current = current.link; } if (current != null) { if (current == tail) tail = prior; if (prior == null) list = list.link; else prior.link = current.link; }}

Search for item

item in last node

item in first node

item in interior node

Page 30: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

30

Linked Structures

Iterator "trio"public void resetList()

{ current = list; }

public boolean hasNext()

{ return current != null; }

public String next(){ String item = current.item; current = current.link; return item;}

What assumptionsmust be in

documentation?

Page 31: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

31

Other Data Structures

What do theseobjects havein common?

Page 32: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

32

Other Data Structures

Stack

A data structure in which insertions and deletions can be made from only one end

LIFO

Last In First Out

Can you name some additional LIFO structures in every day life?

Page 33: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

33

Other Data Structures

Firstitem

called"top"

Page 34: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

34

Other Data Structures

What properties does this illustration exhibit?

Page 35: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

35

Other Data Structures

Queue

A data structure in which insertions are made at one end and deletions are made at the other end

FIFO

First In First Out

Can you name some additional FIFO structures in every day life?

Page 36: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

36

Other Data Structures

Page 37: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

37

Other Data Structures

Page 38: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

38

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

Other Data Structures

Jake's Pizza Shop

What properties does this illustration exhibit?

Page 39: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

39

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

ROOT NODE

Other Data Structures

Page 40: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

40

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEAF NODES

Other Data Structures

Page 41: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

41

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEFT SUBTREE OF ROOT NODE

Other Data Structures

Page 42: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

42

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

RIGHT SUBTREE OF ROOT NODE

Other Data Structures

Page 43: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

43

Other Data Structures

Binary tree

A data structure, each of whose nodes refer to left and right child nodes

Page 44: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

44

Other Data Structures

Binary search tree

A binary tree in which the value in any node is greater than the value in the left child and any of its children and less than the value in its right child and any of its children

Page 45: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

45

Other Data Structures

Binary search trees provide rapid searches

Searchfor50

Page 46: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

46

Other Data Structures

Searchfor18

Wherewould18 be

if there?

Page 47: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

47

Other Data Structures

Inorder(tree)if tree is not NULL

Inorder(Left(tree))Visit Info(tree)Inorder(Right(tree))

PostOrder(tree)if tree is not NULL

Postorder(Left(tree))Postorder(Right(tree))Visit Info(tree)

PreOrder(tree)if tree is not NULL

Visit Info(tree)Preorder(Left(tree))Preorder(Right(tree))alphabetic order

visits leaves first

expression evaluation

Traversals

Page 48: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

48

Other Data Structures

Page 49: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

49

Other Data Structures

Graph

A data

structure in

which the

nodes can

be arranged

in any pattern

Page 50: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

50

Other Data Structures

Hashing

A technique to

perform insertions

and access to an

item in constant

time by using the

value to identify

its location in the

structure

Page 51: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

51

Other Data Structures

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

. . .

Empty

4501

Empty

8903

8

10

values

[ 97]

[ 98]

[ 99]

7803

Empty

.

.

.

Empty

2298

3699

HandyParts company makes no more than 100 different parts, but theparts all have four digit numbers

index = partNum % 100

Hash function

A function used to manipulate the value to produce an index that identifies its location

Page 52: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

52

Use the hash function

Hash(key) = partNum % 100

to place the element with

part number 5502 in the

array

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

. . .

Empty

4501

Empty

8903

8

10

values

[ 97]

[ 98]

[ 99]

7803

Empty

.

.

.

Empty

2298

3699

Other Data Structures

Page 53: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

53

Next place part number6702 in the array

6702 % 100 = 2

But values[2] is already occupied, causing acollision

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

. . .

values

[ 97]

[ 98]

[ 99]

7803

Empty

.

.

.

Empty 2298

3699

Empty

4501

5502

Other Data Structures

Page 54: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

54

One solution

Repeatedly increment indexuntil an empty locationis found for part number 6702

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

. . .

values

[ 97]

[ 98]

[ 99]

7803

Empty

.

.

.

Empty

2298

3699

Empty

4501

5502

Other Data Structures

Page 55: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

55

Part 6702 can be placed atthe location with index 4

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

. . .

values

[ 97]

[ 98]

[ 99]

7803

Empty

.

.

.

Empty

2298

3699

Empty

4501

5502

Hashing

Page 56: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

56

Part 6702 is placed atthe location with index 4

Where would the part withnumber 4598 be placed usingthis scheme?

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

. . .

values

[ 97]

[ 98]

[ 99]

7803

6702

.

.

.

Empty

2298

3699

Empty

4501

5502

Hashing

Page 57: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

57

Other Data Structures

Handling collisions with chaining

Page 58: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

58

Other Data Structures

Comparison of incrementing index and chaining

Page 59: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

59

Generic Types in Java

Generic types

A type for which the operations are defined but the type of the objects being manipulated is not

How have we handled generics previously?

Page 60: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

60

Generic Types in Java

class Node <ItemType extends Comparable<ItemType>>{ Node<ItemType> link = null; ItemType item;

Node() { } Node(ItemType newItem) { item = newItem; }}

Node<ItemType> list;

Node<ItemType> tail;

In client code

Page 61: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

61

Java Collections Framework

Classes that implement Collection are data structures that hold items in an organized manner

Set is Java's list with no duplicates

Interface

Hierarchy

Page 62: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

62

Java Collections Framework

Classes that implement Map hold values in association with objects called keys

Rest of Interface hierarchy

Page 63: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

63

Java Collections Framework

Let's look at this another way

Page 64: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

64

Collection

List Set

SortedSet

AbstractCollection

AbstractList AbstractSet

AbstractSequentialList

Interfaces

Abstract Classes

implements

extends

Page 65: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

65

AbstractList AbstractSetAbstract

SequentialList

LinkedList ArrayList Vector HashSet TreeSet

Observers inAbstractCollectioncontains containsAllisEmptytoArraytoStringsize

StackLinked

HashSet

Concrete Classes

Page 66: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

66

Java Collections Framework

AbstractCollections implements the Iterable Interface that has one method

iterator that returns an Iterator object

Iterator myIter = myList.iterator();

while (myIter.hasNext()) System.out.println(myIter.next());

Page 67: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

67

Java Collections Framework

Collections class contains static helper methods for use with the classes in the collection

void sort(List)int binarySearch(List, key)void reverse(List)void shuffle(List)void copy(DestinationList, SourceList)Object min(Collection)Object max(Collection)boolean replaceAll(List, OldValueObject, NewValueObject)boolean disjoint(Collection, Collection)

Page 68: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

68

Java Collections Framework

ArrayList is a concrete list class using an array-based implementation with the usual list operations and some array-specific methods as well such as:add(index, item) Inserts the item at the index position

set(index, item) Replaces the item at the index position;

returns replaced object

remove(index) Removes the item at the index position

trimToSize() Trim array to list size

ensureCapacity(limit) Makes sure the underlying array has

limit positions

Page 69: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

69

Java Collections Framework

LinkedList is a concrete list class with a linked implementation with the usual list operations and some additional ones such as:

add(index, item) Inserts item at the index position

getFirst() Returns a reference to the first item

getLast() Returns a reference to the last item

poll() Deletes and returns the first element

removeLast() Deletes and returns last element

remove(index) Deletes and returns the item in the index

position

Page 70: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

70

Java Collections Framework

ArrayList and LinkedList also have methods that take collections as arguments

removeAll(collection) Removes all items from list

that match items in collection

retainAll(collection) Removes all items that do not

match items in the collection

addAll(collection) Adds all the items in the collection

to the end of the list

Do these operations add any new functionality?

Page 71: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

71

Java Collections Framework

Sets (a lists without duplicates) is implemented in two concrete classes: HashSet and TreeSet

– Names give the underlying data structure– Both implement all the regular list

operations– TreeSet is able to return subtrees

(collections) with values less than or greater than a parameter

Page 72: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

72

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; while (inFile.hasNextLine()) { line = inFile.nextLine(); list.add(line); } Iterator iterator = list.iterator(); while (iterator.hasNext()) System.out.println(iterator.next());

What will the output look like?

Page 73: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

73

Java Collections Framework

File:redblueyellowbrownblackpinkgreenorangewhitevioletcrimsonrose

Output:redblueyellowbrownblackpinkgreenorangewhitevioletcrimsonrose

Output from

ArrayListimplementation

Page 74: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

74

Java Collections Framework

File:redblueyellowbrownblackpinkgreenorangewhitevioletcrimsonrose

Output:greenroseredwhiteorangecrimsonpinkbrownblueyellowvioletblack

HashSet list = new HashSet();

Output fromHashSet

implementation

Page 75: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

75

Java Collections Framework

File:redblueyellowbrownblackpinkgreenorangewhitevioletcrimsonrose

Output:blackbluebrowncrimsongreenorangepinkredrosevioletwhiteyellow

TreeSet list = new TreeSet();

Output fromTreeSet

implementation

Page 76: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

76

Extras

I designedone of the

best knownsorting

algorithms and wasknighted recently

Who am I

Page 77: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

77

Extras - GUI Track

Handling events with radio buttons requires declaring and instantiating a ButtonGroup

object declaring and instantiating each radio button registering an ActionListener with each

radio button adding each button to ButtonGroup object adding each button to panel parameter to getActionCommand tells which

button was pressed

Page 78: Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

78

Extras - GUI Track

Window withthreeradio

buttonsand a label