Chapter 22. Lists, Stacks, Queues and Priority Queues

Chapter 22 Lists, Stacks, Queues and Priority Queues 1 22.1 Introduction 2 The JCF supports two types of containers • Collections (collection ...
Author: David Buck Hunt
0 downloads 0 Views 307KB Size
Chapter 22 Lists, Stacks, Queues and Priority Queues

1

22.1

Introduction

2

The JCF supports two types of containers

• Collections (collection of items) • Map (key/value pair)

3

22.2

Collections

4

There are three types here: -Set (group of non-duplicate elements) -List (ordered collection of elements) -Queue (elements processed in first-in, first-out order)

The Java Collections Framework's object model

5

Interfaces: define the framework Abstract classes: provide partial implementations for convenience Concrete classes: implement the interfaces with concrete data structures

The three types of collections A

B

Set: store a group of non-duplicate elements

List: stores an ordered collection of elements

Queue: stores elements in a first-in-first-out order

6

Interface and

Collection

22.3

AbstractCollection

Class

7

It all starts with the 
 Collection Interface

8

The AbstractCollection class implements all the methods in the interface except for the size() and iterator() methods.

22.4

Lists

9

A List allows duplicate elements

10

! Elements can be added anywhere in the list ! A ListIterator allows for bidirectional traversal

An ArrayList is resizable

11

A LinkedList offers bidirectional traversal

12

Application Deconstructed
 < TestLinkedList.java > package inclass.collections; import java.util.*; public class TestLinkedList { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add(1); arrayList.add(2); arrayList.add(3); arrayList.add(1); arrayList.add(4); arrayList.add(0, 10); arrayList.add(3, 30);

13

Application Deconstructed
 < TestLinkedList.java > System.out.println("An array list of integers:"); System.out.println(" " + arrayList);

An array list of integers: [10, 1, 2, 30, 3, 1, 4]

14

Application Deconstructed
 < TestLinkedList.java > // Create a linked list. LinkedList linkedList = new LinkedList(arrayList); linkedList.add(1, "red"); linkedList.removeLast(); linkedList.addFirst("green"); System.out.println("\nThe linked list in forward traversal:"); System.out.println(" " + linkedList);

An array list of integers: [10, 1, 2, 30, 3, 1, 4] The linked list in forward traversal: [green, 10, red, 1, 2, 30, 3, 1]

15

Application Deconstructed
 < TestLinkedList.java > // Traverse the linked list backward. ListIterator listIterator = 
 linkedList.listIterator(linkedList.size() ); System.out.println("\nThe linked list in reverse traversal:"); while ( listIterator.hasPrevious() ) { System.out.print( " " + listIterator.previous() ); }

The linked list in forward traversal: [green, 10, red, 1, 2, 30, 3, 1] The linked list in reverse traversal: 1 3 30 2 1 red 10 green

16

22.5

The Comparator Interface

17

A Comparator can be used in the absence of Comparable

18

Application Deconstructed
 import java.util.Comparator; public class GeometricObjectComparator implements Comparator, Serializable { public int compare(GeometricObject o1, GeometricObject o2) { double area1 = o1.getArea(); double area2 = o2.getArea(); int result; if (area1 < area2) else if (area1 == area2) else

{ result = -1; } { result = 0; } { result = 1; }

return result; }

19

Application Deconstructed
 import java.util.Comparator; public class TestComparator { public static void main(String[] args) { GeometricObject rect = new Rectangle(5, 5); GeometricObject circ = new Circle(5); GeometricObject largerOfTheTwo = max(rect, circ,
 new GeometricObjectComparator()); System.out.println("The area of the larger object is " + largerOfTheTwo.getArea()); } // end main()

20

Application Deconstructed
 public static GeometricObject max(GeometricObject go1,
 GeometricObject go2,
 Comparator c) { if (c.compare(go1, go2) > 0) { return go1; } else { return go2; } }

The area of the larger object is 78.53981633974483

21

Application Deconstructed
 import java.util.Comparator; public class GeometricObjectComparator implements Comparator, Serializable { public int compare(GeometricObject o1, GeometricObject o2) { double area1 = o1.getArea(); double area2 = o2.getArea(); int result; if (area1 < area2) else if (area1 == area2) else

{ result = -1; } { result = 0; } { result = 1; }

return result; }

22

Application Deconstructed
 import java.util.*; public class TestTreeWithComparator { public static void main(String[] args) { Set set = new TreeSet(
 new GeometricObjectComparator() ); set.add( set.add( set.add( set.add(

new new new new

Rectangle(4, 5) ); Circle(40) ); Circle(40) ); Rectangle(4, 1) );

23

Application Deconstructed
 System.out.println("A sorted (by area) set of geometric objects"); for (GeometricObject element : set) System.out.println( "area = " + element.getArea() ); } }

A sorted (by area) set of geometric objects area = 4.0 area = 20.0 area = 5022.548245743669

24

22.6

Static Methods for Lists and Collections

25

The Collections class offers lots of goodies

26

Application Deconstructed
 package inclass.collections; import java.util.*; public class TestCollections { public static void main(String[] args) { List list = Arrays.asList("red", "green", "blue"); Collections.sort(list); System.out.println("list, sorted: " + list); } }

list, sorted: [blue, green, red]

27

Application Deconstructed
 // Reverse the list. Collections.sort( list, Collections.reverseOrder() ); System.out.println("list, reverse sorted: " + list);

list, sorted: [blue, green, red] list, reverse sorted: [red, green, blue]

28

Application Deconstructed
 // Search for a key using binary search. Collections.sort(list); System.out.println( "\nred is at index: " + 
 Collections.binarySearch(list, "red") ); System.out.println( "yellow is at index: " + 
 Collections.binarySearch(list, "yellow") );

list, sorted: [blue, green, red] list, reverse sorted: [red, green, blue] red is at index: 2 yellow is at index: -4 29

Application Deconstructed
 // Reverse the list. System.out.println("\nlist: " + list); Collections.reverse(list); System.out.println("list reversed: " + list);

red is at index: 2 yellow is at index: -4 list: [blue, green, red] list reversed: [red, green, blue] 30

Application Deconstructed
 // Shuffle the list. Collections.shuffle(list); System.out.println("\nlist shuffled: " + list); // Shuffle the list predictably. Collections.shuffle( list, new Random(4) ); System.out.println("\nlist shuffled predictably: " + list); Collections.shuffle( list, new Random(4) ); System.out.println("list shuffled predictably: " + list); list: [blue, green, red] list reversed: [red, green, blue] list shuffled: [green, blue, red] list shuffled predictably: [green, blue, red] list shuffled predictably: [green, blue, red] 31

22.8

The Vector and Stack Classes

32

The Vector is thread safe

33

The Stack is a LIFO structure Vector

Stack +Stack() +empty():boolean +peek(): E +pop(): E +push(o: E): E +search(o: Object): int

34

22.9

Queues and Priority Queues

35

The Queue is a FIFO structure

36

! Elements are added to the end of the queue ! Elements are removed from the front of the queue ! poll() returns null if queue is empty ! remove() throws and exception if queue is empty ! peek() returns null if queue is empty ! element() throws an exception if queue is empty

Application Deconstructed
 package inclass.collections; import java.util.*; public class TestQueue { public static void main(String[] args) { Queue queue = new LinkedList(); queue.offer("Oklahoma"); queue.offer("Indiana"); queue.offer("Georgia"); queue.offer("Texas");

37

Application Deconstructed
 System.out.print("Queue elements:\n "); while (queue.size() > 0) { System.out.print(queue.remove() + " "); } } } // end TestQueue

Queue elements: Oklahoma Indiana Georgia Texas

38

The PriorityQueue is ordered by priority

39

! The element with the highest priority is processed (removed) first ! The default ordering is the natural order (ascending) with the least value assigned the highest priority

Application Deconstructed
 package inclass.collections; import java.util.*; public class TestPriorityQueue { public static void main(String[] args) { PriorityQueue queue = new PriorityQueue(); queue.offer("Oklahoma"); queue.offer("Indiana"); queue.offer("Georgia"); queue.offer("Texas");

40

Application Deconstructed
 System.out.print("Priority queue elements using Comparable:\n while (queue.size() > 0) { System.out.print(queue.remove() + " "); }

");

Priority queue elements using Comparable: Georgia Indiana Oklahoma Texas

41



Items entered: Oklahoma, Indiana, Georgia, Texas

Application Deconstructed
 // Create a pq using reverse ordering. PriorityQueue reverseQueue = 
 new PriorityQueue( 4, Collections.reverseOrder() ); reverseQueue.offer("Oklahoma"); reverseQueue.offer("Indiana"); reverseQueue.offer("Georgia"); reverseQueue.offer("Texas");

42

Application Deconstructed
 System.out.print("\n\nPriority queue elements using 
 reverse Comparator:\n "); while (queue.size() > 0) { System.out.print(reverseQueue.remove() + " "); }

Priority queue elements using Comparable: Georgia Indiana Oklahoma Texas Priority queue elements using reverse Comparator: Texas Oklahoma Indiana Georgia

43

Items entered: Oklahoma, Indiana, Georgia, Texas