700 likes | 821 Views
17. Data Structures. Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd ‘Will you walk a little faster?’ said a whiting to a snail, ‘There’s a porpoise close behind us, and he’s treading on my tail.’ Lewis Carroll There is always room at the top.
E N D
17 • Data Structures
Much that I bound, I could not free;Much that I freed returned to me. Lee Wilson Dodd ‘Will you walk a little faster?’ said a whiting to a snail,‘There’s a porpoise close behind us, and he’s treading on my tail.’ Lewis Carroll There is always room at the top. Daniel Webster Push on—keep moving. Thomas Morton I’ll turn over a new leaf. Miguel de Cervantes
OBJECTIVES In this chapter you will learn: • To form linked data structures using references, self-referential classes and recursion. • The type-wrapper classes that enable programs to process primitive data values as objects. • To use autoboxing to convert a primitive value to an object of the corresponding type-wrapper class. • To use auto-unboxing to convert an object of a type-wrapper class to a primitive value. • To create and manipulate dynamic data structures, such as linked lists, queues, stacks and binary trees. • Various important applications of linked data structures. • How to create reusable data structures with classes, inheritance and composition.
17.1 Introduction • 17.2 Type-Wrapper Classes for Primitive Types • 17.3 Autoboxing and Auto-Unboxing • 17.4 Self-Referential Classes • 17.5 Dynamic Memory Allocation • 17.6 Linked Lists • 17.7 Stacks • 17.8 Queues • 17.9 Trees • 17.10 Wrap-Up
17.1 Introduction • Dynamic data structures • Linear data structures • Linked lists • Stacks • Queues • Binary trees
17.2 Type-Wrapper Classes for Primitive Types • Type-wrapper classes • In package java.lang • Enable programmers to manipulate primitive-type values as objects • Boolean, Byte, Character, Double, Float, Integer, Long and Short
17.3 Autoboxing and Auto-Unboxing • Boxing conversion • Converts a value of a primitive type to an object of the corresponding type-wrapper class • Unboxing conversion • Converts an object of a type-wrapper class to a value of the corresponding primitive type • Java automatically performs these conversions (starting with Java SE 5) • Called autoboxing and auto-unboxing
17.4 Self-Referential Classes • Self-referential class • Contains an instance variable that refers to another object of the same class type • That instance variable is called a link • A null reference indicates that the link does not refer to another object • Illustrated by a backslash in diagrams
17.5 Dynamic Memory Allocation • Dynamic memory allocation • The ability for a program to obtain more memory space at execution time to hold new nodes and to release space no longer needed • Java performs automatic garbage collection of objects that are no longer referenced in a program • NodenodeToAdd=newNode(10); • Allocates the memory to store a Node object and returns a reference to the object, which is assigned to nodeToAdd • Throws an OutOfMemoryError if insufficient memory is available
17.6 Linked Lists • Linked list • Linear collection of nodes • Self-referential-class objects connected by reference links • Can contain data of any type • A program typically accesses a linked list via a reference to the first node in the list • A program accesses each subsequent node via the link reference stored in the previous node • Are dynamic • The length of a list can increase or decrease as necessary • Become full only when the system has insufficient memory to satisfy dynamic storage allocation requests
Performance Tip 17.1 • An array can be declared to contain more elements than the number of items expected, but this wastes memory. Linked lists provide better memory utilization in these situations. Linked lists allow the program to adapt to storage needs at runtime.
Performance Tip 17.2 • Insertion into a linked list is fast—only two references have to be modified (after locating the insertion point). All existing node objects remain at their current locations in memory.
Performance Tip 17.3 • Insertion and deletion in a sorted array can be time consuming—all the elements following the inserted or deleted element must be shifted appropriately.
17.6 Linked Lists (Cont.) • Singly linked list • Each node contains one reference to the next node in the list • Doubly linked list • Each node contains a reference to the next node in the list and a reference to the previous node in the list • java.util’s LinkedList class is a doubly linked list implementation
Performance Tip 17.4 • Normally, the elements of an array are contiguous in memory. This allows immediate access to any array element, because its address can be calculated directly as its offset from the beginning of the array. Linked lists do not afford such immediate access to their elements—an element can be accessed only by traversing the list from the front (or from the back in a doubly linked list).
Field data can refer to any object Stores a reference to the next ListNode object in the linked list
References to the first and last ListNodes in a List Call one-argument constructor
Display the list’s contents Display a message indicating that the list is empty Output a string representation of current.data Move to the next node in the list
Insert objects at the beginning of the list using method insertAtFront Insert objects at the end of the list using method insertAtBack JVM autoboxes each literal value in an Integer object
Deletes objects from the front of the list using method removeFromFront Delete objects from the end of the list using method removeFromBack Call List method print to display the current list contents Exception handler for EmptyListException
17.6 Linked Lists (Cont.) • Method insertAtFront’s steps • Call isEmpty to determine whether the list is empty • If the list is empty, assign firstNode and lastNode to the new ListNode that was initialized with insertItem • The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to null • If the list is not empty, set firstNode to a new ListNode object and initialize that object with insertItem and firstNode • The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to the ListNode passed as argument, which previously was the first node
Fig. 17.6 | Graphical representation of operation insertAtFront.
17.6 Linked Lists (Cont.) • Method insertAtBack’s steps • Call isEmpty to determine whether the list is empty • If the list is empty, assign firstNode and lastNode to the new ListNode that was initialized with insertItem • The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to null • If the list is not empty, assign to lastNode and lastNode.nextNode the reference to the new ListNode that was initialized with insertItem • The ListNode constructor sets data to refer to the insertItem passed as an argument and sets reference nextNode to null
Fig. 17.7 | Graphical representation of operation insertAtBack.
17.6 Linked Lists (Cont.) • Method removeFromFront’s steps • Throw an EmptyListException if the list is empty • Assign firstNode.data to reference removedItem • If firstNode and lastNode refer to the same object, set firstNode and lastNode to null • If the list has more than one node, assign the value of firstNode.nextNode to firstNode • Return the removedItem reference
Fig. 17.8 | Graphical representation of operation removeFromFront.
17.6 Linked Lists (Cont.) • Method removeFromBack’s steps • Throws an EmptyListException if the list is empty • Assign lastNode.data to removedItem • If the firstNode and lastNode refer to the same object, set firstNode and lastNode to null • If the list has more than one node, create the ListNode reference current and assign it firstNode • “Walk the list” with current until it references the node before the last node • The while loop assigns current.nextNode to current as long as current.nextNode is not lastNode
17.6 Linked Lists (Cont.) • Assign current to lastNode • Set current.nextNode to null • Return the removedItem reference
Fig. 17.9 | Graphical representation of operation removeFromBack.
17.7 Stacks • Stacks • Last-in, first-out (LIFO) data structure • Method push adds a new node to the top of the stack • Method pop removes a node from the top of the stack and returns the data from the popped node • Program execution stack • Holds the return addresses of calling methods • Also contains the local variables for called methods • Used by the compiler to evaluate arithmetic expressions
17.7 Stacks (Cont.) • Stack class that inherits from List • Stack methods push, pop, isEmpty and print are performed by inherited methods insertAtFront, removeFromFront, isEmpty and print • push calls insertAtFront • pop calls removeFromFront • isEmpty and print can be called as inherited • Other List methods are also inherited • Including methods that should not be in the stack class’s public interface
Class StackInheritance extends class List Method push calls inherited method insertAtFront Method pop calls inherited method removeFromFront
Create a StackInheritenace object Push integers onto the stack
Pop the objects from the stack in an infinite while loop Implicitly call inherited method print Display the exception’s stack trace
17.7 Stacks (Cont.) • Stack class that contains a reference to a List • Enables us to hide the List methods that should not be in our stack’s public interface • Each stack method invoked delegates the call to the appropriate List method • method push delegates to List method insertAtFront • method pop delegates to List method removeFromFront • method isEmpty delegates to List method isEmpty • method print delegates to List method print
Outline privateListreference • StackComposition.java • (1 of 2) push method delegates call to List method insertAtFront
Method pop delegates call to List method removeFromFront Method isEmpty delegates call to List method isEmpty Method print delegates call to List method print
17.8 Queues • Queue • Similar to a checkout line in a supermarket • First-in, first-out (FIFO) data structure • Enqueue inserts nodes at the tail (or end) • Dequeue removes nodes from the head (or front) • Used to support print spooling • A spooler program manages the queue of printing jobs
17.8 Queues (Cont.) • Queue class that contains a reference to a List • Method enqueue calls List method insertAtBack • Method dequeue calls List method removeFromFront • Method isEmpty calls List method isEmpty • Method print calls List method print
An object of class List Method enqueue calls List method insertAtBack
Method dequeue calls List method removeFromFront Method isEmpty calls List method isEmpty Method print calls List method print
Create a Queue object Enqueue four integers