Chapter 12 data structures and collections
This presentation is the property of its rightful owner.
Sponsored Links
1 / 78

Chapter 12 Data Structures and Collections PowerPoint PPT Presentation


  • 76 Views
  • Uploaded on
  • Presentation posted in: General

Chapter 12 Data Structures and Collections. 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

Download Presentation

Chapter 12 Data Structures and Collections

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Chapter 12 data structures and collections

Chapter 12

Data Structures

and Collections


Knowledge goals

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


Skill goals

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


Linked structures

Linked Structures

Array-

based

list is

fixed

size


Linked structures1

Linked Structures

Array-

based is

physically

ordered;

linked is

logically

ordered,

which

means …


Linked structures2

Linked Structures

Insertions

and

deletions

are

easier


Linked structure

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?


Linked structure1

Linked Structure

List

External pointer

A node

Each node contains

item and a link


Linked structures3

Linked Structures

class Node

{

Node link = null;

String item;

Node()

{ item = ""; }

Node(String data)

{ item = data; }

}

null is a keyword

meaning points to

nothing

default

constructor

parameterized

constructor


Linked structures4

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


Linked structures5

Linked Structures

  • list = new Node("Adams");

  • current = list;

Result


Linked structures6

Linked Structures

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

Result


Linked structures7

Linked Structures

  • current = current.link;

Result


Linked structures8

Linked Structures

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

  • current = current.link;

Result


Linked structures9

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?


Linked structures10

Linked Structures

Which of these

will change

with the

linked

version?


Linked structures11

Linked Structures

Does the CRC card

for a class change

with the

implementation?


Linked structures12

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

}


Linked structures13

Linked Structures

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

Search

when

item

is not

in the

list


Linked structures14

Linked Structures

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

    • Can keep a counter

      increment with each insertion

      decrement with each deletion

    • Can count the number of items each time

Which is best (better)?


Linked structures15

Linked Structures

  • public int size()

  • {

  • Node current = list;

  • int numItems = 0;

  • while (current != null)

  • {

  • numItems++;

  • current = current.link;

  • }

  • return numItems;

  • }

Is this an

example

of a

traversal?


Linked structures16

Linked Structures

  • Mutators

  • Add

    • 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


Linked structure2

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 list

Set list and tail

to item

Not empty list

Set item as last node

Set tail to last node


Linked structures17

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


Linked structures18

Linked Structures

Can't be reached;

System recaptures it


Linked structures19

Linked Structures

Remove "Adams"

What is prior?


Linked structures20

Linked Structures

Remove "Carter"


Linked structures21

Linked Structures

Remove "Adams" (only node)


Chapter 12 data structures and collections

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


Linked structures22

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

assumptions

must be in

documentation?


Other data structures

Other Data Structures

What do these

objects have

in common?


Other data structures1

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?


Other data structures2

Other Data Structures

First

item

called

"top"


Other data structures3

Other Data Structures

What properties does this illustration exhibit?


Other data structures4

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?


Other data structures5

Other Data Structures


Other data structures6

Other Data Structures


Other data structures7

Other Data Structures

Jake's Pizza Shop

Owner

Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper

Joyce Chris Max Len

What properties does this illustration exhibit?


Other data structures8

ROOT NODE

Other Data Structures

Owner

Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper

Joyce Chris Max Len


Other data structures9

LEAF NODES

Other Data Structures

Owner

Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper

Joyce Chris Max Len


Other data structures10

Other Data Structures

Owner

Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper

Joyce Chris Max Len

LEFT SUBTREE OF ROOT NODE


Other data structures11

Other Data Structures

Owner

Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper

Joyce Chris Max Len

RIGHT SUBTREE

OF ROOT NODE


Other data structures12

Other Data Structures

  • Binary tree

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


Other data structures13

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


Other data structures14

Other Data Structures

  • Binary search trees provide rapid searches

Search

for

50


Other data structures15

Other Data Structures

Search

for

18

Where

would

18 be

if there?


Other data structures16

Other Data Structures

Traversals

PreOrder(tree)

if tree is not NULL

Visit Info(tree)

Preorder(Left(tree))

Preorder(Right(tree))

  • 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)

alphabetic order

expression evaluation

visits leaves first


Other data structures17

Other Data Structures


Other data structures18

Other Data Structures

Graph

A data

structure in

which the

nodes can

be arranged

in any pattern


Other data structures19

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


Chapter 12 data structures and collections

values

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

.

.

.

Empty

4501

Empty

8903

8

10

7803

Empty

.

.

.

Empty

2298

3699

[ 97]

[ 98]

[ 99]

Other Data Structures

HandyParts company

makes no more than 100

different parts, but the

parts 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


Other data structures20

values

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

.

.

.

Empty

4501

Empty

8903

8

10

7803

Empty

.

.

.

Empty

2298

3699

[ 97]

[ 98]

[ 99]

Other Data Structures

Use the hash function

Hash(key) = partNum % 100

to place the element with

part number 5502 in the

array


Other data structures21

Other Data Structures

values

Next place part number

6702 in the array

6702 % 100 = 2

But values[2] is already

occupied, causing a

collision

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

.

.

.

Empty

4501

5502

7803

Empty

.

.

.

Empty

2298

3699

[ 97]

[ 98]

[ 99]


Other data structures22

Other Data Structures

values

One solution

Repeatedly increment index

until an empty location

is found for part number 6702

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

.

.

.

Empty

4501

5502

7803

Empty

.

.

.

Empty

2298

3699

[ 97]

[ 98]

[ 99]


Hashing

Hashing

values

Part 6702 can be placed at

the location with index 4

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

.

.

.

Empty

4501

5502

7803

Empty

.

.

.

Empty

2298

3699

[ 97]

[ 98]

[ 99]


Hashing1

Hashing

values

Part 6702 is placed at

the location with index 4

Where would the part with

number 4598 be placed using

this scheme?

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

.

.

.

Empty

4501

5502

7803

6702

.

.

.

Empty

2298

3699

[ 97]

[ 98]

[ 99]


Other data structures23

Other Data Structures

Handling collisions with chaining


Other data structures24

Other Data Structures

Comparison of incrementing index and chaining


Generic types in java

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?


Generic types in java1

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


Java collections framework

Java Collections Framework

Interface

Hierarchy

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

Set is Java's list with no duplicates


Java collections framework1

Java Collections Framework

Rest of Interface hierarchy

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


Java collections framework2

Java Collections Framework

Let's look at this another way


Chapter 12 data structures and collections

Interfaces

Collection

List

Set

SortedSet

Abstract Classes

AbstractCollection

AbstractList

AbstractSet

implements

AbstractSequentialList

extends


Chapter 12 data structures and collections

Abstract

SequentialList

AbstractList

AbstractSet

LinkedList

ArrayList

Vector

HashSet

TreeSet

Observers in

AbstractCollection

contains

containsAll

isEmpty

toArray

toString

size

Linked

HashSet

Stack

Concrete Classes


Java collections framework3

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());


Java collections framework4

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)


Java collections framework5

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


Java collections framework6

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


Java collections framework7

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?


Java collections framework8

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


Chapter 12 data structures and collections

  • publicstaticvoid 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?


Java collections framework9

File:

red

blue

yellow

brown

black

pink

green

orange

white

violet

crimson

rose

Output:

red

blue

yellow

brown

black

pink

green

orange

white

violet

crimson

rose

Java Collections Framework

Output

from

ArrayList

implementation


Java collections framework10

File:

red

blue

yellow

brown

black

pink

green

orange

white

violet

crimson

rose

Output:

green

rose

red

white

orange

crimson

pink

brown

blue

yellow

violet

black

Java Collections Framework

HashSet list = new HashSet();

Output from

HashSet

implementation


Java collections framework11

File:

red

blue

yellow

brown

black

pink

green

orange

white

violet

crimson

rose

Output:

black

blue

brown

crimson

green

orange

pink

red

rose

violet

white

yellow

Java Collections Framework

TreeSet list = new TreeSet();

Output from

TreeSet

implementation


Extras

Extras

I designed

one of the

best known

sorting

algorithms

and was

knighted

recently

Who am I


Extras gui track

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


Extras gui track1

Extras - GUI Track

Window

with

three

radio

buttons

and a

label


  • Login