Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 15 – The Java Collections Framework
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 15 – The Java Collections Framework
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
To learn how to use the collection classes supplied in the Java library
To use iterators to traverse collections
To choose appropriate collections for solving programming problems
To study applications of stacks and queues
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
An Overview of the Collections Framework
Why do we need collections of objects?
• When we are only creating a few objects, we can afford to declare individualized reference variables for these objects:
• E.g. Students s1, s2, s3,
• E.g. Professors profA, profB, profC.
• At other times, individualized reference variables are impractical.
• Too large no. of objects to create:
– E.g. university course catalog might have hundreds of courses
• We do not know until runtime how many objects to create
– So we can’t predefine no. of reference variables at compile time
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Fortunately, Java solve this problem by collection
• Special category of object
What are Collections?
• Way to gather up objects as they are created
• We can manage them as a group
• We can operate on them collectively
• We can refer to them individually when necessary
• Collections hold and organize References to Other Objects
• Not objects themselves!
• E.g. ArrayList
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
A collection organizes references to objects that live in memory outside of the collection:
BankAccount Object
BankAccount Object
BankAccount Object
An ArrayList Object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
An Overview of the Collections Framework
Java collections framework: • a hierarchy of interface types and classes for collecting objects.
• Each interface type is implemented by one or more classes
• E.g. List interface is implemented by classes: ArrayList, Stack and linkedList
• Refer JavaDoc to find out implementing classes
Figure 1 Interfaces and Classes in the Java Collections Framework
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
An Overview of the Collections Framework
The Collection interface is at the root
• All Collection classes implement this interface
• Refer javadoc api
• So all have a common set of methods
• Adding objects : Collections automatically expand as new items are added.
• Removing objects: Collections automatically shrink when items are removed.
• Retrieving specific individual objects
• Iterating through the objects in some predetermined order
• Getting a count of the number of objects presently referenced by the collection
• Answering a true/false question as to whether a particular object’s reference is in the collection or not
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Three Generic Types of Collection:
1. Ordered lists
2. Dictionaries
3. Sets
Ordered Lists Sets
Dictionaries/Maps
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
1. Ordered Lists:
• Allows us to insert items in a particular order
• Allow later retrieving them in that same order
• Specific objects can also be retrieved based on their position in the list
• Most collection types(e.g. ordered lists, dictionaries, sets) needn’t be assigned an explicit capacity at the time that they are instantiated
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
• By default, items are added at the end of an ordered list
• unless explicit instructions are given to insert an item at a different position.
• E.g. a student waiting list:
• Order maintenance is important to be fair in selecting students from waiting list
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
An Overview of the Collections Framework
• Ordered lists are realized in java using List interface and/or Queue interface
• List is a collection that remembers the order of its elements.
• Refer javadoc api
• Several predefined Java classes implement the notion of ordered list collections:
• ArrayList
• Stack
• Vector
• LinkedList (List+Queue)
• PriorityQueue (Queue)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Interface List
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Interface Queue:
• Add items to one end (the tail) and remove them from the other end (the head) (First-In First-Out FIFO)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
2. Dictionaries/ Maps• Provides a means for storing each object reference along with a
unique lookup key that can later be used to quickly retrieve the object
• The key is often selected based on one or more of the object’s attribute values.
• E.g. a Student object’s student ID number would make an excellent key, because its value is inherently unique for each Student.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
Example map (set of <key, value> pairs )
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
Items in a dictionary can typically also be iterated through one by one, in ascending key (or some other predetermined) order.
Maps are realized in java using Map interface
• Set of <key,Value> pairs.
• Refer javadoc api
• Key provide easy/faster lookup of objects based on key
• E.g. you can lookup a student object based on student id
• Key must be unique to value
• Map has no duplicate keys
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Some predefined Java classes that implement the notion of a dictionary are:
• HashMap
• TreeMap
• The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time
• guaranteed log(n) time cost for the containsKey, get, put and remove operations
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
3. Sets• An unordered collection
• i.e. you CANNOT ask for a particular item by number/position once it has been inserted into the set.
• We can iterate though elements one by one
• But, order is not predetermined
• Duplicate entries aren’t allowed in a set
• Unlike lists
• E.g. group employees by department
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Realized using Set interface
• Refer javadoc api
Two predefined Java classes that implement the notion of a set are:
• HashSet
• TreeSet
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
Question
A gradebook application stores a collection of quizzes. Should it use a list or a set?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Answer
A list is a better choice because the application will want to retain the order in which the quizzes were given.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Question
A student information system stores a collection of student records for a university. Should it use a list or a set?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Answer
A set is a better choice. There is no intrinsically useful ordering for the students. For example, the registrar's office has little use for a list of all students by their GPA.
By storing them in a set, adding, removing, and finding students can be efficient.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Question
Why is a queue of books a better choice than a stack for organizing your required reading?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Answer
With a stack, you would always read the latest required reading, and you might never get to the oldest readings.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
Question
As you can see from Figure 1, the Java collections framework does not consider a map a collection. Give a reason for this decision.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
Answer
A collection stores elements, but a map stores associations between elements.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Let’s now look at some important Collection classes in detail:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Linked Lists A data structure used for collecting a sequence of objects:
Allows efficient addition and removal of elements in the middle of the sequence.
A linked list consists of a number of nodes• Each node stores element + has a reference to the next node.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Linked Lists
Adding and removing elements in the middle of a linked list is efficient.
Visiting the elements of a linked list in sequential order is efficient.
Random access is NOT efficient.
Figure 6 Example of a linked list
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
Linked Lists
When inserting or removing a node:
• Only the neighboring node references need to be updated
• Unlike arrays!
Figure 7 Inserting a Node into a Linked List
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
Linked Lists
Figure 8 Removing a Node From A Linked List
Visiting the elements of a linked list in sequential order is efficient.
Random access is NOT efficient.
When to use a linked list:
• You are concerned about the efficiency of inserting or removing elements
• You rarely need element access in random order
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
The LinkedList Class of the Java Collections Framework
Generic class
• Specify type of elements in angle brackets: LinkedList<Product> = new LinkedList<Product>();
LinkedList<Integer> = new LinkedList<Integer>();
Package: java.util
• LinkedList has the methods of the Collection interface.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
The LinkedList Class of the Java Collections Framework
Some additional LinkedList methods:
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
List Iterator Use a list iterator to access elements inside a linked list.
Think of an iterator as pointing between two elements:
To get a list iterator, use the listIterator method of the LinkedList class.
LinkedList<String> employeeNames = new ListIterator<String>();
ListIterator<String> iterator = employeeNames.listIterator();
Also a generic type.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
List Iterator Initially points before the first element.
Move the position with next method:if (iterator.hasNext()){ iterator.next();}
The next method returns the element that the iterator is passing.
The return type of the next method matches the list iterator's type parameter.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
List Iterator To traverse all elements in a linked list of strings
Using while loop:while (iterator.hasNext()){ String name = iterator.next(); //Do something with name}
To use the “for each” loop:for (String name : employeeNames){ //Do something with name}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
List Iterator The nodes of the LinkedList class store two links:
• One to the next element
• One to the previous element
• Called a doubly-linked list
To move the list position forward, use methods:
• hasNext
• next
To move the list position backwards, use methods:
• hasPrevious
• previous
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
List Iterator The add method:
• adds an object after the iterator.
• Then moves the iterator position past the new element.
iterator.add("Juliet");
Figure 8 A Conceptual View of the List Iterator
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
List Iterator The remove method:
• Removes object that was returned by the last call to next or previous
• To remove all names that fulfill a certain condition:while (iterator.hasNext()){ String name = iterator.next(); if (condition is fulfilled for name) iterator.remove();}
• Be careful when calling remove:
• It can be called only ONCE after calling next or previous
• You CANNOT call it immediately after a call to add
• If you call it improperly, it throws an IllegalStateException
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
List Iterator ListIterator interface extends Iterator interface.
Methods of the Iterator and ListIterator interfaces
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Programming Question Write a tester class ListDemo that :
• Create a linked list staff to maintain names of staff of a company.
• Inserts 4 names into the end of the list (Diana, Harry, Romeo, Tom)
• Iterates through the list (use ListIterator)
• After iterating the second element, add two new names (Juliet, Nina)
• Remove the last traversed element
• Prints the list
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
Answer 1 import java.util.LinkedList; 2 import java.util.ListIterator; 3 4 /** 5 This program demonstrates the LinkedList class. 6 */ 7 public class ListDemo 8 { 9 public static void main(String[] args) 10 { 11 LinkedList<String> staff = new LinkedList<String>(); 12 staff.addLast("Diana"); 13 staff.addLast("Harry"); 14 staff.addLast("Romeo"); 15 staff.addLast("Tom"); 16 17 // | in the comments indicates the iterator position 18 19 ListIterator<String> iterator = staff.listIterator(); // |DHRT 20 iterator.next(); // D|HRT 21 iterator.next(); // DH|RT 22 23 // Add more elements after second element 24 25 iterator.add("Juliet"); // DHJ|RT 26 iterator.add("Nina"); // DHJN|RT 27 28 iterator.next(); // DHJNR|T 29 30 // Remove last traversed element 31
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
32 iterator.remove(); // DHJN|T 33 34 // Print all elements 35 36 System.out.println(staff); 37 System.out.println("Expected: [Diana, Harry, Juliet, Nina, Tom]"); 38 } 39 }
Program Run:
[Diana Harry Juliet Nina Tom]Expected: [Diana Harry Juliet Nina Tom]
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
Question
Do linked lists take more storage space than arrays of the same size?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
Answer
Yes, for two reasons. 1. A linked list needs to store the neighboring node
references, which are not needed in an array.
2. Moreover, there is some overhead for storing an object. In a linked list, each node is a separate object that incurs this overhead, whereas an array is a single object.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Programming Question
Modify ListDemo class by writing a loop that removes all names with length less than 5 from staff list.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Answer
ListIterator<String> iter = staff.iterator();
while (iter.hasNext()){ String str = iter.next(); if (str.length() < 5) { iter.remove(); }}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Question
Answer:ListIterator<String> iter = words.iterator();while (iter.hasNext()){ System.out.println(iter.next()); if (iter.hasNext()) { iter.next(); // Skip the next element }}
Write a loop that prints every second element of a linked list of strings called words.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Sets A set organizes its values in an order that is optimized for efficiency.
May not be the order in which you add elements.
Inserting and removing elements is more efficient with a set than with a list.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
Sets The Set interface has the same methods as the Collection
interface.
A set does not admit duplicates.
Two implementing classes
• HashSet
o based on hash table
• TreeSet
o based on binary search tree
A Set implementation arranges the elements so that it can locate them quickly.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
Sets HashSet:
• Elements are internally grouped according to a hashcode
• E.g. Try MD5 algorithm hash generation:
echo -n 'text to be encrypted' | md5sum –
• E.g. Try SHA1 algorithm hash generation:
echo -n "yourpassword" | openssl sha1
E.g.
• HashSet<String> set1 = new HashSet<String>();
• Set<Rectangle> set2 = new HashSet<Rectangle>();
• HashSet<HashSet<Integer>> = new HashSet<HashSet<Integer>>();
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Sets
TreeSet
• Elements are kept in sorted order
• The nodes are arranged in a tree shape, not in a linear sequence
• You can form tree sets for any class that implements the Comparable interface:
• Example: String or Integer.
• Use a TreeSet if you want to visit the set's elements in sorted order.
• Otherwise choose a HashSet
o It is a bit more efficient — if the hash function is well chosen
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Sets Store the reference to a TreeSet or HashSet in a Set<String>
variable:
Set<String> names = new HashSet<String>();
Or
Set<String> names = new TreeSet<String>();
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Working with Sets Adding and removing elements:
names.add("Romeo");names.remove("Juliet");
Sets don't have duplicates.
• Adding a duplicate is ignored.
Attempting to remove an element that isn't in the set is ignored.
The contains method tests whether an element is contained in the set:
if (names.contains("Juliet")) . . .
• The contains method uses the equals method of the element type
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
Working with Sets To process all elements in the set, get an iterator.
A set iterator visits the elements in the order in which the set implementation keeps them.Iterator<String> iter = names.iterator();while (iter.hasNext()){ String name = iter.next(); //Do something with name}
You can also use the “for each” loopfor (String name : names){ //Do something with name}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Working with Sets
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
Programming Question Write a class called SpellCheck. In main method implement following:
• Read all the correctly spelled words from a dictionary file (ch15\section_3\words)
• Put them in a set dictinaryWords
• Reads all words from a document (ch15\section_3\alice30.txt)
• Put them in a second set documentWords
• To read file into a set, implement readWords method:Set<String> dictionaryWords = readWords("words"); ...public static Set<String> readWords(String filename) throws FileNotFoundException
• Print all the words in the second set that are not in the dictionary set.
• This will leave out potential misspellings in documentWords
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
Answer 1 import java.util.HashSet; 2 import java.util.Scanner; 3 import java.util.Set; 4 import java.io.File; 5 import java.io.FileNotFoundException; 6 7 /** 8 This program checks which words in a file are not present in a dictionary. 9 */ 10 public class SpellCheck 11 { 12 public static void main(String[] args) 13 throws FileNotFoundException 14 { 15 // Read the dictionary and the document 16 17 Set<String> dictionaryWords = readWords("words"); 18 Set<String> documentWords = readWords("alice30.txt"); 19 20 // Print all words that are in the document but not the dictionary 21 22 for (String word : documentWords) 23 { 24 if (!dictionaryWords.contains(word)) 25 { 26 System.out.println(word); 27 } 28 } 29 } 30
Continued
SpellCheck.java
Copyright © 2014 by John Wiley & Sons. All rights reserved. 65
31 /** 32 Reads all words from a file. 33 @param filename the name of the file 34 @return a set with all lowercased words in the file. Here, a 35 word is a sequence of upper- and lowercase letters. 36 */ 37 public static Set<String> readWords(String filename) 38 throws FileNotFoundException 39 { 40 Set<String> words = new HashSet<String>(); 41 Scanner in = new Scanner(new File(filename)); 42 // Use any characters other than a-z or A-Z as delimiters 43 in.useDelimiter("[^a-zA-Z]+"); 44 while (in.hasNext()) 45 { 46 words.add(in.next().toLowerCase()); 47 } 48 return words; 49 } 50 }
Program Run:neighbouringcroquetedpennyworthdutchesscomfitsxiidinnclamour
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
Question
Arrays and lists remember the order in which you added elements; sets do not. Why would you want to use a set instead of an array or list?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
Answer
Adding and removing elements as well as testing for membership is more efficient with sets.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
Question
Why are set iterators different from list iterators?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Answer
Sets do not have an ordering, so it doesn't make sense to add an element at a particular iterator position, or to traverse a set backward.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 70
Programming Question
Modify the SpellCheck program to use a TreeSet instead of a HashSet. How would the output change?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 71
Answer
The words would be listed in sorted order.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 72
Maps A map allows you to associate elements from a key set with elements from a
value collection.
Use a map when you want to look up objects by using a key.
Figure 10 A Map
Copyright © 2014 by John Wiley & Sons. All rights reserved. 73
Maps Two implementations of the Map interface:
• HashMap
• TreeMap
Store the reference to the map object in a Map reference:
Map<String, Color> favoriteColors = new HashMap<String, Color>();
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved. 74
Maps Use the put method to add an association:
favoriteColors.put("Juliet", Color.RED);
You can change the value of an existing association by calling put again:
favoriteColors.put("Juliet", Color.BLUE);
The get method returns the value associated with a key:
Color favorite = favorite.get("Juliet");
• If you ask for a key that isn't associated with any values, the get method returns null.
To remove an association, call the remove method with the key:
favoriteColors.remove("Juliet");
Copyright © 2014 by John Wiley & Sons. All rights reserved. 75
Working with Maps
Copyright © 2014 by John Wiley & Sons. All rights reserved. 76
Maps Sometimes you want to enumerate all keys in a map.
The keySet method yields the set of keys.
Ask the key set for an iterator and get all keys.
For each key, you can find the associated value with the get method.
To print all key/value pairs in a map m:Set<String> keySet = m.keySet();for (String key : keySet){ Color value = m.get(key); System.out.println(key + "->" + value);}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 77
Programming Question Implement the tester class MapDemo. In the main method, create a
map called favoriteColors with person name as the key and favorite color of the person as value. Then add <key,value> pairs based on following diagram:
Finally print all <key,value> pairs in the map.
Program Run:
Juliet : java.awt.Color[r=0,g=0,b=255]Adam : java.awt.Color[r=255,g=0,b=0]Eve : java.awt.Color[r=0,g=0,b=255]Romeo : java.awt.Color[r=0,g=255,b=0]
Copyright © 2014 by John Wiley & Sons. All rights reserved. 78
Answer 1 import java.awt.Color; 2 import java.util.HashMap; 3 import java.util.Map; 4 import java.util.Set; 5 6 /** 7 This program demonstrates a map that maps names to colors. 8 */ 9 public class MapDemo 10 { 11 public static void main(String[] args) 12 { 13 Map<String, Color> favoriteColors = new HashMap<String, Color>(); 14 favoriteColors.put("Juliet", Color.BLUE); 15 favoriteColors.put("Romeo", Color.GREEN); 16 favoriteColors.put("Adam", Color.RED); 17 favoriteColors.put("Eve", Color.BLUE); 18 19 // Print all keys and values in the map 20 21 Set<String> keySet = favoriteColors.keySet(); 22 for (String key : keySet) 23 { 24 Color value = favoriteColors.get(key); 25 System.out.println(key + " : " + value); 26 } 27 } 28 }
MapDemo.java
Copyright © 2014 by John Wiley & Sons. All rights reserved. 79
Question
Answer: A set stores elements. A map stores associations between keys and values.
What is the difference between a set and a map?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 80
Answer
A set stores elements. A map stores associations between keys and values.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 81
Question
Why is the collection of the keys of a map a set and not a list?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 82
Answer
The ordering does not matter, and you cannot have duplicates
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
Question
Why is the collection of the values of a map not a set?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
Answer
Because it might have duplicates.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Question
Suppose you want to track how many times each word occurs in a document. Declare a suitable map variable.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Answer
Answer:Map<String, Integer> wordFrequency;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
Question
What is a Map<String, HashSet<String>>? Give a possible use for such a structure.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 88
Answer
Answer: It associates strings with sets of strings. One application would be a thesaurus that lists synonyms for a given word. For example, the key "improve" might have as its value the set ["ameliorate", "better", "enhance", "enrich", "perfect", "refine"].
Copyright © 2014 by John Wiley & Sons. All rights reserved. 89
Choosing a Collection Determine how you access the values.
Determine the element types or key/value types.
Determine whether element or key order matters.
For a collection, determine which operations must be efficient.
For hash sets and maps, decide whether you need to implement the hashCode and equals methods.
If you use a tree, decide whether to supply a comparator.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 90
Stacks A stack lets you insert and remove elements only at one end:
• Called the top of the stack.
• Removes items in the opposite order than they were added
• Last-in, first-out or LIFO order
Add and remove methods are called push and pop.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 91
Stacks Example
Stack<String> s = new Stack<String>();s.push("A");s.push("B");s.push("C");while (s.size() > 0){ System.out.print(s.pop() + " "); // Prints C B A}
The last pancake that has been added to this stack will be the first one that is consumed.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 92
Stack Animator:
• Array implementation:
• http://www.cs.usfca.edu/~galles/visualization/StackArray.html
• List Implementation:
• http://www.cs.usfca.edu/~galles/visualization/StackLL.html
Copyright © 2014 by John Wiley & Sons. All rights reserved. 93
Stacks Many applications for stacks in computer science.
Consider: Undo function of a word processor
• The issued commands are kept in a stack.
• When you select “Undo”, the last command is popped off the stack and undone
Run-time stack that a processor or virtual machine:
• Stores the values of variables in nested methods.
• When a new method is called, its parameter variables and local variables are pushed onto a stack.
• When the method exits, they are popped off again.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 94
Stack in the Java Library Stack class provides push, pop and peek methods.
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved. 95
Programming Question Implement a tester ckass StackDemo. The main method should do
following:
• create a stack to hold integers.
• Add values 1,2,3 to the stack.
• Print stack content
• Remove top element
• Print stack after removal
A sample program run is shown:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 96
Answer
import java.util.*;
public class StackDemo { public static void main(String args[]) { // creating stack Stack<Integer> st = new Stack<Integer>(); // populating stack st.push(Integer.valueOf(1)); st.push(Integer.valueOf(2)); st.push(Integer.valueOf(3)); //elements before remove System.out.println("Elelments before removal: "+st); // removing top object System.out.println("Removed object is: "+st.pop()); // elements after remove System.out.println("Elements after remove: "+st); } }
StackDemo.java
Copyright © 2014 by John Wiley & Sons. All rights reserved. 97
Queue A queue
• Lets you add items to one end of the queue (the tail)
• Remove items from the other end of the queue (the head)
• Items are removed in the same order in which they were added
• First-in, first-out or FIFO order
To visualize a queue, think of people lining up.
Typical application: a print queue.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 98
Queue The Queue interface in the standard Java library has:
• an add method to add an element to the tail of the queue,
• A remove method to remove the head of the queue, and
• A peek method to get the head element of the queue without removing it.
The LinkedList class implements the Queue interface.
When you need a queue, initialize a Queue variable with a LinkedList object:Queue<String> q = new LinkedList<String>();q.add("A");q.add("B");q.add("C");while (q.size() > 0) { System.out.print(q.remove() + " "); }// Prints A B C
Copyright © 2014 by John Wiley & Sons. All rights reserved. 99
Queue
Copyright © 2014 by John Wiley & Sons. All rights reserved. 100
Queue Animator:
• Queues: Array Implementation
• Queues: Linked List Implementation
Copyright © 2014 by John Wiley & Sons. All rights reserved. 101
Question
Why would you want to declare a variable asQueue<String> q = new LinkedList<String>();
instead of simply declaring it as a linked list?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 102
Answer
This way, we can ensure that only queue operations can be invoked on the q object.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 103
Stack and Queue Applications A stack can be used to check whether parentheses in an expression
are balanced.When you see an opening parenthesis, push it on the stack.When you see a closing parenthesis, pop the stack.If the opening and closing parentheses don't match The parentheses are unbalanced. Exit.If at the end the stack is empty The parentheses are balanced.Else The parentheses are not balanced.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 104
Stack and Queue Applications Walkthrough of the sample expression:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 105
Stack and Queue Applications Use a stack to evaluate expressions in reverse Polish notation.
If you read a number
Push it on the stack.
Else if you read an operand
Pop two values off the stack.
Combine the values with the operand.
Push the result back onto the stack.
Else if there is no more input
Pop and display the result.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 106
Stack and Queue Applications Walkthrough of evaluating the expression 3 4 5 + ×:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 107
section_6_2/Calculator.java 1 import java.util.Scanner; 2 import java.util.Stack; 3 4 /** 5 This calculator uses the reverse Polish notation. 6 */ 7 public class Calculator 8 { 9 public static void main(String[] args) 10 { 11 Scanner in = new Scanner(System.in); 12 Stack<Integer> results = new Stack<Integer>(); 13 System.out.println("Enter one number or operator per line, Q to quit. "); 14 boolean done = false; 15 while (!done) 16 { 17 String input = in.nextLine(); 18 19 // If the command is an operator, pop the arguments and push the result 20 21 if (input.equals("+")) 22 { 23 results.push(results.pop() + results.pop()); 24 } 25 else if (input.equals("-")) 26 { 27 Integer arg2 = results.pop(); 28 results.push(results.pop() - arg2); 29 } Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 108
section_6_2/Calculator.java 30 else if (input.equals("*") || input.equals("x")) 31 { 32 results.push(results.pop() * results.pop()); 33 } 34 else if (input.equals("/")) 35 { 36 Integer arg2 = results.pop(); 37 results.push(results.pop() / arg2); 38 } 39 else if (input.equals("Q") || input.equals("q")) 40 { 41 done = true; 42 } 43 else 44 { 45 // Not an operator--push the input value 46 47 results.push(Integer.parseInt(input)); 48 } 49 System.out.println(results); 50 } 51 } 52 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 109
Evaluating Algebraic Expressions with Two Stacks
Using two stacks, you can evaluate expressions in standard algebraic notation.
• One stack for numbers, one for operators
Evaluating the top: 3 + 4
Copyright © 2014 by John Wiley & Sons. All rights reserved. 110
Evaluating Algebraic Expressions with Two Stacks
Evaluate 3 x 4 + 5
• Push until you get to the +
• x (top of operator stack) has higher precedence than + , so evaluate the top
Copyright © 2014 by John Wiley & Sons. All rights reserved. 111
Evaluating Algebraic Expressions with Two Stacks
Evaluate 3 + 4 × 5
• Add x to the operator stack so we can get the next number
Copyright © 2014 by John Wiley & Sons. All rights reserved. 112
Evaluating Algebraic Expressions with Two Stacks
• Keep operators on the stack until they are ready to be evaluated
Copyright © 2014 by John Wiley & Sons. All rights reserved. 113
Evaluating Algebraic Expressions with Two Stacks
Evaluating parentheses: 3 × (4 + 5)
• Push ( on the stack
• Keep pushing until we reach the )
• Evaluate until we find the matching (
Copyright © 2014 by John Wiley & Sons. All rights reserved. 114
Evaluating Algebraic Expressions with Two Stacks
The algorithmIf you read a number Push it on the number stack.Else if you read a ( Push it on the operator stack.Else if you read an operator op While the top of the stack has a higher precedence than op Evaluate the top. Push op on the operator stack.Else if you read a ) While the top of the stack is not a ( Evaluate the top. Pop the (.Else if there is no more input While the operator stack is not empty Evaluate the top.
At the end, the value on the number stack the the value of the expression
Copyright © 2014 by John Wiley & Sons. All rights reserved. 115
Evaluating Algebraic Expressions with Two Stacks
Helper method to evaluate the top: Pop two numbers off the number stack.Pop an operator off the operator stack.Combine the numbers with that operator.Push the result on the number stack.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 116
References From : Beginning Java Objects, JACQUIE BARKER