Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 13 Collections Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Copyright © 2012 Pearson Education, Inc. Collections • A collection is an object that helps us organize and manage other objects • Chapter 13 focuses on: – the concept of a collection – separating the interface from the implementation – dynamic data structures – linked lists – queues and stacks – trees and graphs – generics Copyright © 2012 Pearson Education, Inc. Outline Collections and Data Structures Dynamic Representations Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc. Collections • A collection is an object that serves as a repository for other objects • A collection provides services for adding, removing, and otherwise managing the elements it contains • Sometimes the elements in a collection are ordered, sometimes they are not • Sometimes collections are homogeneous, containing all the same type of objects, and sometimes they are heterogeneous Copyright © 2012 Pearson Education, Inc. Abstraction • Collections can be implemented in many different ways • Collections should be abstractions – That is, they should hide unneeded details • We want to separate the interface of the structure from its underlying implementation • This helps manage complexity and makes it possible to change the implementation without changing the interface Copyright © 2012 Pearson Education, Inc. Abstract Data Types • An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information • The set of operations defines the interface to the ADT • In one sense, as long as the ADT fulfills the promises of the interface, it doesn't matter how the ADT is implemented • Objects are a good programming mechanism to create ADTs because their internal details are encapsulated Copyright © 2012 Pearson Education, Inc. Quiz • Does the ArrayList class provide an abstract data type? • Why ArrayList is called in that way if it implements the List<E> interface? Copyright © 2012 Pearson Education, Inc. Quiz • Does the ArrayList class provide an abstract data type? – Yes. It provides a collection of information and operations for storing and accessing the information. The implementation details are hidden – we do not know how it is implemented. • Why ArrayList is called in that way if it implements the List<E> interface? – Because the implementation of this ADT is based on an array. So, the implementation is hidden but we may understand the cost of the operations – for better programming. Copyright © 2012 Pearson Education, Inc. Outline Collections and Data Structures Dynamic Representations Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc. Dynamic Structures • A static data structure has a fixed size • This meaning is different from the meaning of the static modifier • Arrays are static; once you define the number of elements it can hold, the size doesn’t change • A dynamic data structure grows and shrinks at execution time as required by its contents • A dynamic data structure is implemented using object references as links Copyright © 2012 Pearson Education, Inc. Object References • Recall that an object reference is a variable that stores the address of an object • A reference also can be called a pointer • References often are depicted graphically: student John Smith 40725 3.58 Copyright © 2012 Pearson Education, Inc. References as Links • Object references can be used to create links between objects • Suppose a class (Node) contains a reference to another object of the same class: class Node { Student info; Node next; } Copyright © 2012 Pearson Education, Inc. References as Links • References can be used to create a variety of linked structures, such as a linked list: Copyright © 2012 Pearson Education, Inc. A Sequence of Railroads Cars Each car is loaded with an "object" Intermediate Nodes • The objects being stored should not be concerned with the details of the data structure in which they may be stored • For example, the Student class should not have to store a link to the next Student object in the list • Instead, use a separate node class with two parts: – a reference to an independent object – a link to the next node in the list • The internal representation becomes a linked list of nodes Copyright © 2012 Pearson Education, Inc. Magazine Collection • Let’s explore an example of a collection of Magazine objects, managed by the MagazineList class, which has an private inner class called MagazineNode • See MagazineRack.java • See MagazineList.java • See Magazine.java Copyright © 2012 Pearson Education, Inc. //******************************************************************* // MagazineRack.java Author: Lewis/Loftus // // Driver to exercise the MagazineList collection. //******************************************************************* public class MagazineRack { //---------------------------------------------------------------// Creates a MagazineList object, adds several magazines to the // list, then prints it. //---------------------------------------------------------------public static void main (String[] args) { MagazineList rack = new MagazineList(); rack.add rack.add rack.add rack.add rack.add (new (new (new (new (new Magazine("Time")); Magazine("Woodworking Today")); Magazine("Communications of the ACM")); Magazine("House and Garden")); Magazine("GQ")); System.out.println (rack); } } Copyright © 2012 Pearson Education, Inc. Output //******************************************************************* // MagazineRack.java Author: Lewis/Loftus Time // // Driver to exercise Woodworking the MagazineList Today collection. //******************************************************************* Communications of the ACM House and Garden public class MagazineRack GQ { //---------------------------------------------------------------// Creates a MagazineList object, adds several magazines to the // list, then prints it. //---------------------------------------------------------------public static void main (String[] args) { MagazineList rack = new MagazineList(); rack.add rack.add rack.add rack.add rack.add (new (new (new (new (new Magazine("Time")); Magazine("Woodworking Today")); Magazine("Communications of the ACM")); Magazine("House and Garden")); Magazine("GQ")); System.out.println (rack); } } Copyright © 2012 Pearson Education, Inc. //******************************************************************* // MagazineList.java Author: Lewis/Loftus // // Represents a collection of magazines. //******************************************************************* public class MagazineList { private MagazineNode list; //---------------------------------------------------------------// Sets up an initially empty list of magazines. //---------------------------------------------------------------public MagazineList() { list = null; } continue Copyright © 2012 Pearson Education, Inc. continue //---------------------------------------------------------------// Creates a new MagazineNode object and adds it to the end of // the linked list. //---------------------------------------------------------------public void add (Magazine mag) { MagazineNode node = new MagazineNode (mag); MagazineNode current; if (list == null) // 'list' points to the first magazine list = node; // if it is present else { current = list; while (current.next != null) current = current.next; current.next = node; } } continue Copyright © 2012 Pearson Education, Inc. continue //---------------------------------------------------------------// Returns this list of magazines as a string. //---------------------------------------------------------------public String toString () { String result = ""; MagazineNode current = list; while (current != null) { result += current.magazine + "\n"; current = current.next; } return result; } continue Copyright © 2012 Pearson Education, Inc. continue //***************************************************************** // An inner class that represents a node in the magazine list. // The public variables are accessed by the MagazineList class. //***************************************************************** private class MagazineNode { public Magazine magazine; public MagazineNode next; //-------------------------------------------------------------// Sets up the node //-------------------------------------------------------------public MagazineNode (Magazine mag) { magazine = mag; next = null; } } } Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Magazine.java Author: Lewis/Loftus // // Represents a single magazine. //******************************************************************** public class Magazine { private String title; //----------------------------------------------------------------// Sets up the new magazine with its title. //----------------------------------------------------------------public Magazine (String newTitle) { title = newTitle; } //----------------------------------------------------------------// Returns this magazine as a string. //----------------------------------------------------------------public String toString () { return title; } } Copyright © 2012 Pearson Education, Inc. Inserting a Node • A node can be inserted into a linked list with a few reference changes: Copyright © 2012 Pearson Education, Inc. Quick Check Write code that inserts newNode after the node pointed to by current. Copyright © 2012 Pearson Education, Inc. Quick Check Write code that inserts newNode after the node pointed to by current. newNode.next = current.next; current.next = newNode; Copyright © 2012 Pearson Education, Inc. Deleting a Node • Likewise, a node can be removed from a linked list by changing the next pointer of the preceding node: Copyright © 2012 Pearson Education, Inc. Other Dynamic Representations • It may be convenient to implement a list as a doubly linked list, with next and previous references: Copyright © 2012 Pearson Education, Inc. Other Dynamic Representations • Another approach is to use a separate header node, with a count and references to both the front and rear of the list: Copyright © 2012 Pearson Education, Inc. Outline Collections and Data Structures Dynamic Representations Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc. Classic Data Structures • Now we'll examine some common data structures that are helpful in many situations • Classic linear data structures include queues and stacks • Classic nonlinear data structures include trees and graphs Copyright © 2012 Pearson Education, Inc. Queues • A queue is a list that adds items only to the rear of the list and removes them only from the front • It is a FIFO data structure: First-In, First-Out • Analogy: a line of people at a bank teller’s window Copyright © 2012 Pearson Education, Inc. Queues • Classic operations for a queue: – enqueue - add an item to the rear of the queue – dequeue (or serve) - remove an item from the front of the queue – empty - returns true if the queue is empty • Queues often are helpful in simulations or any situation in which items get “backed up” while awaiting processing Copyright © 2012 Pearson Education, Inc. Quiz • Show the content of a queue after the following operations are performed (assuming that at the beginning the queue is empty): enqueue(5); enqueue(9); dequeue(); enqueue(5); enqueue(10); dequeue(); dequeue(); Copyright © 2012 Pearson Education, Inc. Quiz • Show the content of a queue after the following operations are performed (assuming that at the beginning the queue is empty): enqueue(5); 5 enqueue(9); 95 dequeue(); 9 enqueue(5); 59 enqueue(10); 10 5 9 dequeue(); 10 5 dequeue(); 10 Copyright © 2012 Pearson Education, Inc. Queues • A queue can be represented by a singly-linked list; it is most efficient if the references point from the front toward the rear of the queue • A queue can be represented by an array, using the remainder operator (%) to “wrap around” when the end of the array is reached and space is available at the front of the array Copyright © 2012 Pearson Education, Inc. Queue as Linked List public class Queue { private Node head = null; // Points to first Node in the queue. private Node tail = null; // Points to last Node in the queue. private int size; // Number of items on the queue. void enqueue(Info info) { // Add the specified Info object to the end of the queue. Node newTail = new Node(); newTail.info = info; if (head == null) { head = newTail; tail = newTail; } else { tail.next = newTail; tail = newTail; } size++; } … continue ! Queue as Linked List Info dequeue() { // Remove and return the first item in the queue. // (Note that this will throw a NullPointerException // if the queue is empty.) Info firstInfo = head.info; head = head.next; if (head == null) tail = null; size--; return firstInfo; } boolean isEmpty() { // Return true if the queue is empty. return head == null; } int getSize() { // Return the number of items on the queue. return size; } } Stacks • A stack ADT is also linear, like a list or a queue • Items are added and removed from only one end of a stack • It is therefore LIFO: Last-In, First-Out • Analogies: a stack of plates or a stack of books Copyright © 2012 Pearson Education, Inc. Stacks • Stacks often are drawn vertically: Copyright © 2012 Pearson Education, Inc. Stacks • Classic stack operations: – push - add an item to the top of the stack – pop - remove an item from the top of the stack – peek (or top) - retrieves the top item without removing it – empty - returns true if the stack is empty • A stack can be represented by a singly-linked list, with the first node in the list being to top element on the stack • A stack can also be represented by an array, with the bottom of the stack at index 0 Quiz • Show the content of a stack after the following operations are performed. Assume the stack is initially empty. push(5); push(9); pop(); push(5); push(10) pop(); pop(); Copyright © 2012 Pearson Education, Inc. Quiz • Show the content of a stack after the following operations are performed. Assume the stack is initially empty. push(5); 5 push(9); 95 pop(); 5 push(5); 55 push(10) 10 5 5 pop(); 55 pop(); 5 Copyright © 2012 Pearson Education, Inc. Stacks • The java.util package contains a Stack class • The Stack operations operate on Object references • Suppose a message has been encoded by reversing the letters of each word • See Decode.java Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Decode.java Author: Lewis/Loftus // // Demonstrates the use of the Stack class. //******************************************************************** import java.util.*; public class Decode { //----------------------------------------------------------------// Decodes a message by reversing each word in a string. //----------------------------------------------------------------public static void main (String[] args) { Scanner scan = new Scanner (System.in); Stack word = new Stack(); String message; int index = 0; System.out.println ("Enter the coded message:"); message = scan.nextLine(); System.out.println ("The decoded message is:"); continue Copyright © 2012 Pearson Education, Inc. continue while (index < message.length()) { // Push word onto stack while (index < message.length() && message.charAt(index) != ' ') { word.push (new Character(message.charAt(index))); index++; } // Print word in reverse while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); index++; } System.out.println(); } } Copyright © 2012 Pearson Education, Inc. continue Sample Run the coded message: while (index <Enter message.length()) artxE eseehc esaelp { Theonto decoded // Push word stack message is: while (index < message.length() Extra cheese please&& message.charAt(index) != ' ') { word.push (new Character(message.charAt(index))); index++; } // Print word in reverse while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); index++; } System.out.println(); } } Copyright © 2012 Pearson Education, Inc. Outline Collections and Data Structures Dynamic Representations Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc. Trees • A tree is a non-linear data structure that consists of a root node and potentially many levels of additional nodes that form a hierarchy • Nodes that have no children are called leaf nodes • Nodes except for the root and leaf nodes are called internal nodes • In a general tree, each node can have many child nodes. Copyright © 2012 Pearson Education, Inc. A General Tree Copyright © 2012 Pearson Education, Inc. Binary Trees • In a binary tree, each node can have no more than two child nodes • Trees are typically represented using references as dynamic links • For binary trees, this requires storing only two links per node: to the left and right child class TreeNode { ! !int item; !// The data in this node. !TreeNode left; !// Pointer to the left subtree.! !TreeNode right; // Pointer to the right subtree.! }! Copyright © 2012 Pearson Education, Inc. Binary Tree Representation Printing the Items in a Binary Tree (I) public void preorderPrint( TreeNode root ) { ! if ( root != null ) { ! ! !// (Otherwise, there’s nothing to print.)! System.out.print( root.item + " " ); ! ! !// Print the root item. ! preorderPrint( root.left ); !! ! !// Print items in left subtree. ! preorderPrint( root.right ); ! ! !// Print items in right subtree.! }! }! Printing the Items in a Binary Tree (II) public void postorderPrint( TreeNode root ) { ! if ( root != null ) { ! ! !// (Otherwise, there’s nothing to print.)! postorderPrint( root.left ); !! ! !// Print items in left subtree. ! postorderPrint( root.right ); ! ! !// Print items in right subtree.! System.out.print( root.item + " " ); ! ! !// Print the root item. ! }! }! Printing the Items in a Binary Tree (III) public void inorderPrint( TreeNode root ) { ! if ( root != null ) { ! ! !// (Otherwise, there’s nothing to print.)! inorderPrint( root.left ); !! ! !// Print items in left subtree. ! System.out.print( root.item + " " ); ! ! !// Print the root item. ! inorderPrint( root.right ); ! ! !// Print items in right subtree.! }! }! Binary Sorted Tree Binary sort tree: for every node in the tree, the item in that node is greater than every node in the left subtree of that node and it is less than or equal to all the items in the right subtree of that node. Graphs • A graph is another non-linear structure • Unlike a tree, a graph does not have a root • Any node in a graph can be connected to any other node by an edge • Analogy: the highway system connecting cities on a map Copyright © 2012 Pearson Education, Inc. Graphs Copyright © 2012 Pearson Education, Inc. Digraphs • In a directed graph or digraph, each edge has a specific direction • Edges with direction sometimes are called arcs • Analogy: airline flights between airports Copyright © 2012 Pearson Education, Inc. Digraphs Copyright © 2012 Pearson Education, Inc. Representing Graphs • Both graphs and digraphs can be represented using dynamic links or using arrays. • As always, the representation should facilitate the intended operations and make them convenient to implement Copyright © 2012 Pearson Education, Inc. Outline Collections and Data Structures Dynamic Representations Linear Structures (Queues & Stacks) Non-Linear Structures (Trees & Graphs) The Java Collections API Copyright © 2012 Pearson Education, Inc. Collection Classes • The Java standard library contains several classes that represent collections, often referred to as the Java Collections API • Their underlying implementation is implied in the class names such as ArrayList and LinkedList • Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap Copyright © 2012 Pearson Education, Inc. Generics • As mentioned in Chapter 5, Java supports generic types, which are useful when defining collections • A class can be defined to operate on a generic data type which is specified when the class is instantiated: LinkedList<Book> myList = new LinkedList<Book>(); • By specifying the type stored in a collection, only objects of that type can be added to it • Furthermore, when an object is removed, its type is already established Copyright © 2012 Pearson Education, Inc. Summary • Chapter 13 has focused on: – the concept of a collection – separating the interface from the implementation – dynamic data structures – linked lists – queues and stacks – trees and graphs – generics Copyright © 2012 Pearson Education, Inc.