Download Java Collections: List, Sets, Maps

Document related concepts
no text concepts found
Transcript
The Java Collections Framework
You can proceed project phase 2 once we
Complete this.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
 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
• Most collection needn’t be assigned an explicit capacity at the time that they
are instantiated
• Collections can grow and shrink as needed.
• Cannot hold basic data type elements
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
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
Figure 1 Interfaces and Classes in the Java Collections Framework
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
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.
4
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
 Three Generic Types of Collection:
1.
Ordered lists
2.
Dictionaries /Maps
3.
Sets
Ordered Lists
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Dictionaries/Maps
Sets
6
1. Ordered Lists:
• Allows us to insert items in a particular order
• Allow later retrieving them in that same order
• E.g. a student waiting list:
• Order maintenance is important to be fair in selecting students from
waiting list
• Ordered lists are realized in java using :
• List interface
• Queue interface
Copyright © 2014 by John Wiley & Sons. All rights reserved.
7
 Interface List
Copyright © 2014 by John Wiley & Sons. All rights reserved.
8
ArrayList
 Resizable-array implementation of the List interface.
 To declare an array list of strings
ArrayList<Student> waitinglist = new ArrayList<Student>()
 Angle brackets < > denote a type parameter
Refer javadoc API ArrayList class page
Copyright © 2014 by John Wiley & Sons. All rights reserved.
9
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
Declaring and Using Array Lists
 ArrayList<String> is first constructed, it has size 0:
ArrayList<String> names = new ArrayList<String>();
 size method

The size method gives the current size of the array list.
names.size(); //returns 0
 add method

Use the add method to add an object to the end of the array list:
names.add("Emily"); //Now names has size 1 and element "Emily”
names.add("Bob"); //Now names has size 2 and elements "Emily", "Bob”
names.add("Cindy"); //names has size 3 and elements "Emily","Bob",and "Cindy”
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
Example
Add element 1
Add element 2
Add element 3
Copyright © 2014 by John Wiley & Sons. All rights reserved.
12
 Add method [contd.]
• To add a new element at middle of array list :
names.add(1, "Ann"); //add element “Ann” at index==1
• moves all elements with index 1 or larger by one position.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
13
Example
Index =
0
1
Index =
0
1
2
2
3
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Declaring and Using Array Lists
 get method
 To obtain an array list element at a given index, use the get method
•
E.g.
•
The last valid index is:
String name = names.get(0);
//return element at index 0
names.size() - 1
 set method
 To set an array list element to a new value, use the set method:
names.set(2, "Carolyn");
 To add a new element at middle of array list :
names.add(1, "Ann"); //add element “Ann” at index==1
•
moves all elements with index 1 or larger by one position.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
15
Example
Get elements
Set element 2
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Declaring and Using Array Lists
 remove method
1.
removes the element at a given position
2.
moves all elements after the removed element down by one position
3.
and reduces the size of the array list by 1.
names.remove(1);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
Example
List before removing element at index 1
Index =
0
1
2
3
List after removing element at index 1
Index =
0
1
2
Copyright © 2014 by John Wiley & Sons. All rights reserved.
18
Programming Question
 Write a tester class ArrayListDemo to display the words of a file (words.txt) as a list:
1. Read file content to an arrayList allWords
•
Hint: Use Scanner class:
Scanner input = new Scanner(new File("words.txt"));
2. Print elements in allWords
3. Print elements in allWords in reverse order
Note: create and save words.txt with following content.
words.txt
It
is
a
beautiful
day
Find next template next slide:
A sample run is sown below:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
19
template
import java.io.File;
public class ArrayListDemo
{
public static void main(String args[])throws Exception
{
//TODO: create arraylist allWords of type string
//TODO: create a scanner to read words from a file words.txt
//TODO: populate allWords list with words read from file
while (input.hasNext()) {
//TODO: read next input
//TODO: inser input word to allWords list
}
//TODO: print allWords elements in inserted order
//TODO: print allWords elements in reverse order
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
Answer
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
public class ArrayListDemo
{
public static void main(String args[])throws Exception
{
//populate allwords
ArrayList<String> allWords = new ArrayList<String>();
Scanner input = new Scanner(new File("words.txt"));
while (input.hasNext()) {
String word = input.next();
allWords.add(word);
}
//print allwords
System.out.println(allWords);
//print in reverse order
for(int i=allWords.size()-1; i>=0;i--) {``
System.out.print(allWords.get(i)+",");
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
21
Using the Enhanced for Loop with Array Lists
 E.g. print elements in arraylist names:
for (String name : names){
Change ArrayListDemo to use
enhanced for loop
System.out.println(name);
}
 This is equivalent to:
for (int i = 0; i < names.size(); i++){
String name = names.get(i);
System.out.println(name);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
public class ArrayListDemo1
{
public static void main(String args[])throws Exception
{
ArrayList<String> allWords = new ArrayList<String>();
Scanner input = new Scanner(new File("words.txt"));
while (input.hasNext()) {
String word = input.next();
allWords.add(word);
}
//TODO: print allWords elements in inserted order
//System.out.println(allWords);
//
for(int i=0; i<allWords.size();i++) {
//
System.out.print(allWords.get(i)+",");
//
}
for(String s: allWords)
{
System.out.println(s);
}
System.out.println();
for(int i=allWords.size()-1; i>=0;i--) {
System.out.print(allWords.get(i)+",");
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
23
Copying Array Lists
 Copying an array list reference yields two references to the same array list.
 E.g. After the code below is executed
ArrayList<String> friends = names;
friends.add("Harry");
Figure 19 Copying an Array List Reference
Copyright © 2014 by John Wiley & Sons. All rights reserved.
24
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
25
Copying Array Lists
 To make a true copy of an array list, construct the copy and pass the
original list into the constructor:
ArrayList<String> newNames = new ArrayList<String>(names);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
Wrapper Classes
 You cannot directly insert primitive type values into array lists (or any
other collection type).
 Use the matching wrapper class.
 E.g. To collect double values in an array list, you use an
ArrayList<Double>.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
Storing Input Values in an Array List
 To collect an unknown number of inputs, use array lists :
ArrayList<Double> inputs = new ArrayList<Double>();
while (in.hasNextDouble())
{
inputs.add(in.nextDouble());
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29
Question
 Removing Matches:
ArrayList<String> words = ...;
for (int i = 0; i < words.size(); i++)
{
String word = words.get(i);
if (word.length() < 4)
{
words.remove(i);
}
}
 What is the purpose of the code?
 What is wrong with the code?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Answer
 Purpose: remove all words with length<4 from list.
 Error:
• When element is removed indexes automatically change for
following elements
• So, should not increment i when an element is removed
 Correct Pseudocode:
If the element at index i matches the condition
Remove the element.
Else
Increment i.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Can you rewrite previous code?
31
Removing Matches
 Use a while loop, not a for loop
int i = 0;
while (i < words.size()){
String word = words.get(i);
if (word.length() < 4) { words.remove(i); }
else { i++; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
32
Choosing Between Array Lists and Arrays
 For most programming tasks, array lists are easier to use than arrays
• Array lists can grow and shrink.
• Arrays have a nicer syntax.
 Recommendations
• If the size of a collection never changes, use an array.
• If you collect a long sequence of primitive type values and you are concerned
about efficiency, use an array.
• Otherwise, use an array list.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
33
Programming Question
 Write ArrayListDemo2 class to define an ArrayList values to read and
store user input numbers (user can quit any time by typing Q).
 Write code that find and print the largest in the values array list
marking the largest.
 A sample program run is shown:
Please enter values, Q to quit:
35 80 115 44.5 Q
35
80
115 <== largest value
44.5
Find template in next slide:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
Use following template to get started:
public class ArrayListDemo2
{
public static void main(String[] args)
{
//TODO: declare arraylist values
// TODO: Read inputs to values
// TODO: Find the largest
// TODO: Print all values, marking the largest
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
Answer
ArrayListDemo2.java
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListDemo2
{
public static void main(String[] args)
{
//create arraylist
ArrayList<Double> values = new ArrayList<Double>();
// Read inputs
System.out.println("Please enter values, Q to quit:");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble()) {
values.add(in.nextDouble());
}
// Find the largest
double largest = values.get(0);
for (int i = 1; i < values.size(); i++)
if (values.get(i) > largest) {
largest = values.get(i);
}
}
{
// Print all values, marking the largest
for (double element : values)
{
System.out.print(element);
if (element == largest)
{ System.out.print(" <== largest value");
System.out.println();
}
}
}
Copyright
© 2014 by John Wiley & Sons. All rights reserved.
}
36
Linked Lists
 Doubly-linked list implementation of the List interface.
 A linked list consists of a number of nodes
 Each node stores element + a references to the next node
and previous node.
• Visiting the elements of a linked list in sequential order is efficient.
• Random access is NOT efficient.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
Linked Lists
 Adding and removing elements in the middle of a linked list is efficient.
 When inserting/adding or removing a node:
• Only the neighboring node references need to be updated (Unlike arrays!)
Adding a new node with element=“Romeo”
Removing node with element=“Diana”
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Linked Lists
 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.
39
The LinkedList Class of the Java Collections Framework
 Creating empty LinkedList object:
LinkedList<Product> l= new LinkedList<Product>();
LinkedList<String> l= new LinkedList<String>();
 Some methods:
l.add("C");
l.addLast("Z"); //add as last element
l.addFirst("A"); //add as first element
l.remove(2);
l.removeFirst(); //remove first element
ll.removeLast(); //remove last element
Refer javadoc api
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
Question
 Which of the following are valid java statements?
1. List<String> l= new LinkedList<String>();
2. Queue<String> l= new LinkedList<String>();
3. Set<String> l= new LinkedList<String>();
4. Collection<String> l= new LinkedList<String>();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Answer
Dictionaries/Maps
Ordered Lists
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Sets
42
List Iterator
 Use a list iterator to access elements inside a linked list.
 To get a list iterator, use the listIterator method of the
LinkedList class.
LinkedList<String> employeeNames = new LinkedList<String>();
ListIterator<String> iterator = employeeNames.listIterator();
 To iterate forward one element use :
iterator.next()
 To iterate backward one element use:
iterator.previous()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
List Iterator
 To traverse all elements in a linked list of strings, use next() method:
Using while loop:
while (iterator.hasNext())
{
String name = iterator.next();//return next element and moves
iterator position past it
//Do something with name
}
 Smilar to “for each” loop:
for (String name : employeeNames)
{
//Do something with name
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
 Iterate forward:
while (iterator.hasNext())
{
String name = iterator.next();//return next element and moves
iterator position past it
//Do something with name
}
 Iterate backwards:
while (iterator.hasPrevious())
{
String name = iterator.previous();//return previous element and moves
iterator position past it
//Do something with name
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
Example
import java.util.LinkedList;
import java.util.ListIterator;
public class ListIteratorDemo
{
public static void main(String args[])
{
LinkedList<String> l = new LinkedList<String>();
l.add("A");
l.add("B");
l.add("C");
Try it!
//iterate list forward
System.out.println("List:");
ListIterator<String> iterator = l.listIterator(); // |ABC
while (iterator.hasNext())
{
String name = iterator.next(); // A|BC -> AB|C -> ABC|
System.out.println(name);
}
//iterate list backward
System.out.println("List backword:");
ListIterator<String> iterator2 = l.listIterator(); // |ABC
while (iterator.hasPrevious())
{
String name = iterator.previous(); // AB|C -> A|BC -> |ABC
Copyright © 2014 by John Wiley & Sons. All rights reserved.
System.out.println(name);
48
List Iterator
 iterator points between two elements:
 add method:
• adds an object after the iterator.
• Then moves the iterator position past the new element.
iterator.add("Juliet");
iterator.next()
iterator.add(“J”)
Figure 8 A Conceptual View of the List Iterator
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
List Iterator
 remove method:
• Removes object 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.
50
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
51
Programming Question
Write LinkedListDemo class by writing a loop that removes
all names with length less than 5 from staff list. Use a list
iterator
Use following template:
public class LinkedListDemo2{
public static void main(String[] args) {
LinkedList<String> staff = new LinkedList<String>();
staff.addLast("Diana");
staff.addLast("Harry");
staff.addLast("Romeo");
staff.addLast("Tom");
System.out.println("list before:"+staff);
//TODO: remove names with length<5
System.out.println("list after:"+staff);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
Answer
LinkedListDemo.java
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList<String> staff = new LinkedList<String>();
staff.addLast("Diana");
staff.addLast("Harry");
staff.addLast("Romeo");
staff.addLast("Tom");
System.out.println("list before:"+staff);
ListIterator<String> iter = staff.listIterator(); // |DHRT
while (iter.hasNext())
{
String str = iter.next();
if (str.length() < 5) { iter.remove(); }
}
System.out.println("list after:"+staff);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
53
Homework: Programming Question
 Write a tester class LinkedListDemo2 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)
• Create a list iterator for staff list
• Iterates through the list (use ListIterator):
• Iterate first two elements
• After iterating the second element, add two new names (Juliet, Nina)
• Remove the last traversed element
• Prints the list
Program template
in next slide
Copyright © 2014 by John Wiley & Sons. All rights reserved.
54
public class LinkedListDemo2 {
public static void main(String[] args) {
//create linked list staff
//add 4 elements: Diana, Harry, Romeo, Tom
//create a list iterator for staff list
//iterate first two elements
// Add elements Juliet and Nina after second element
// Remove last traversed element
// Print all elements
System.out.println("Expected: [Diana, Harry, Juliet, Nina, Tom]");
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
Answer
LinkedListDemo.java
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListDemo2 {
public static void main(String[] args) {
LinkedList<String> staff = new LinkedList<String>();
staff.addLast("Diana");
staff.addLast("Harry");
staff.addLast("Romeo");
staff.addLast("Tom");
// | in the comments indicates the iterator position
ListIterator<String> iterator = staff.listIterator(); // |DHRT
iterator.next(); // D|HRT
iterator.next(); // DH|RT
// Add more elements after second element
iterator.add("Juliet"); // DHJ|RT
iterator.add("Nina"); // DHJN|RT
iterator.next(); // DHJNR|T
// Remove last traversed element
iterator.remove(); // DHJN|T
// Print all elements
System.out.println(staff);
System.out.println("Expected: [Diana, Harry, Juliet, Nina, Tom]");
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Queue
 A queue
• FIFO- First In First Out data structure
• 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
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.
58
Example
New element is added to the end of the list
Remove element at head (FIFO)
Peek at head element. List unchanged
Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
Queue
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
 Queue Animator:
• Queues: Array Implementation
• http://www.cs.usfca.edu/~galles/visualization/QueueArray.html
• Queues: Linked List Implementation
• http://www.cs.usfca.edu/~galles/visualization/QueueLL.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
2. Sets
•
An unordered collection
–
•
We can iterate though elements one by one
–
•
i.e. you CANNOT ask for a particular item by number/position once it
has been inserted into the set.
But, order is not predetermined
Duplicate entries aren’t allowed in a set
–
Unlike lists
•
E.g. group employees by department
•
Inserting and removing elements is more efficient with a set
than with a list.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
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.
63
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.
64
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.
65
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.
66
Set
 Realized using Set interface
• Refer javadoc api
 Question:
• What are classes implementing Set interface?
(use java API to find out)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
Sets
 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.
68
Sets
 HashSet:
• Elements are internally grouped according to a hashcode
• A hashCode digests input data into a single hash value (a 32-bit signed integer).
• 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.
• Set<Rectangle> set1 = new HashSet<Rectangle>();
• HashsetSet<Rectangle> set2 = new HashSet<Rectangle>();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
69
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
70
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
(must implement compareTo method):
• 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
• E.g.
Set<String> names = new HashSet<String>();
Set<String> names = new TreeSet<String>();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
71
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
72
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.
73
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” loop
for (String name : names)
{
//Do something with name
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
74
Working with Sets
Copyright © 2014 by John Wiley & Sons. All rights reserved.
75
Programming Question
 Write a class called SetDemo with a method solve:
public static void solve(List<String> list1, String[]a2)
 This method, given a list of Strings list1, list2, find two sets s1 and s2 formed from
list1 and list2, respectively , by removing duplicate elements .
 Then find their union s3 = s1  s2 , intersection s4 = s1 s2 and symmetric
difference s5 = ( s1 – s2 )(s2–s1) and print them.
 Note that s1 and s2 must not be changed during the computation of s3, s4 and s5.
 Sample run (given list1=[“Harry”, “Diana”, “Romeo”, “Tom”], list2={“Jim”, “Harry”,
“Diana”}):
s2
s1
> run SetDemo
s1 = [Diana, Harry, Tom, Romeo]
s2 = [Diana, Harry, Jim]
s1 union s2 = [Diana, Harry, Jim, Tom, Romeo]
s1 intersection s2 = [Diana, Harry]
( s1 – s2 )union (s2–s1) = [Jim, Tom, Romeo]
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Romeo
Harry
Tom
Diana
Jim
Find program
template in next
slide
76
Intersection : s1  s2
Union: s1  s2
Difference: s1 - s2  s2 – s1
Copyright © 2014 by John Wiley & Sons. All rights reserved.
77
Program template
public class SetDemo{
public static void main(String[] args) {
List<String> l1 = new ArrayList<String>();
l1.add("Harry ");
l1.add(" Diana ");
l1.add("Romeo");
l1.add("Tom");
List<String> l2 = new ArrayList<String>();
l2.add("Diana ");
l2.add(" Harry ");
l2.add("Jim");
solve(l1, l2);
}
public static void solve(List<String> list1, String[]a2)
{
// TODO: create set s1 from list1
// TODO: create set s2 from list2
// TODO: create and print set s3 = s1 union s2
// TODO: create and print s4 = s1 intersection s2
// TODO: create and print s5 = ( s1 – s2 )union (s2–s1).
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
78
Answer
import
import
import
import
SetDemo.java
java.util.Set;
java.util.List;
java.util.ArrayList;
java.util.HashSet;
public class SetDemo{
public static void main(String[] args) {
List<String> l1 = new ArrayList<String>();
l1.add("Harry ");
l1.add(" Diana ");
l1.add("Romeo");
l1.add("Tom");
List<String> l2 = new ArrayList<String>();
l2.add("Diana ");
l2.add(" Harry ");
l2.add("Jim");
solve(l1, l2);
}
public static void solve(List<String> list1, List<String> list1)
Set<String> s1 = new HashSet<String>(list1) ;
Set<String> s2 = new HashSet<String>( list2) ;
//s3 = s1 union s2
Set<String> s3 = new HashSet<String>(s1);
s3.addAll(s2);
System.out.println("s1 union s2 = "+s3);
//s4 = s1 intersection s2
Set<String> s4 = new HashSet<String>(s1);
s4.retainAll(s2);
System.out.println("s1 intersection s2 = "+s4);
//s5 = ( s1 – s2 )union (s2–s1).
Set<String> s1Subs2= new HashSet<String>(s1); //s1-s2
s1Subs2.removeAll(s2);
Set<String> s2Subs1 = new HashSet<String>(s2); //s2-s1
s2Subs1.removeAll(s1);
Set<String> s5= new HashSet<String>();
s5.addAll(s1Subs2 );
s5.addAll(s2Subs1 );
System.out.println("( s1 – s2 )union (s2–s1) = "+s5);
Copyright
© 2014 by John Wiley & Sons. All rights reserved.
}
{
79
Homework: Programming Question
 Save and run following program to see output. Change HashSet to
Treeset. How does your output change?
import java.util.Set;
import java.util.TreeSet;
import java.util.HashSet;
public class SetDemo2 {
public static void main(String args[]) {
Set<String> s = new HashSet<String>();
s.add("C");
s.add("A");
s.add("B");
s.add("E");
s.add("F");
s.add("D");
System.out.println(s);
for(String str:s)
System.out.print(str+",");
System.out.println();
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
80
Question
 Can you declare a TreeSet of any type?
 E.g. Given Employee class (with name and id attributes), is it
possible to create a TreeSet of Employees in Java?
SetDemo3.java
import java.util.Set;
import java.util.TreeSet;
import java.util.HashSet;
public class SetDemo3 {
public static void main(String args[]) {
Set<Employee> s = new TreeSet<Employee>();
// Add elements to the tree set
s.add(new Employee("Jim", 1));
s.add(new Employee("Andy", 2));
s.add(new Employee("Brandon", 4));
s.add(new Employee("Sam", 3));
System.out.println(s);
Employee.java
public class Employee {
private String name;
private int id;
public Employee(String name,int id){
this.name = name;
this.id = id;
}
public String toString(){
return "[Employee:name="+name+"
id="+id+"]";
}
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
81
Answer: No
Copyright © 2014 by John Wiley & Sons. All rights reserved.
82
Answer
 For a class to be used as element type in a TreeSet, class MUST
implement Comparable interface
 Some java library classes implement Comparable. E.g.:
• String
• Integer
• (all wrapper classes)
• Date
Copyright © 2014 by John Wiley & Sons. All rights reserved.
83
Copyright © 2014 by John Wiley & Sons. All rights reserved.
84
Comparable Interface
 A class implementing Comparable interface should implement
compareTo method
For two object obj1 , obj2 of same type, a call of obj1.compareTo( obj2) should
return:
• a value < 0 if obj1 comes "before" obj2 in the ordering (obj1 < obj2)
• usually return -1
• a value > 0 if obj1 comes "after" obj2 in the ordering, (obj1 > obj2)
• usually return 1
• exactly 0 if obj1 and obj2 are considered "equal" in the ordering (obj1 = obj2)
• return 0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
85
• Example class implementing Comparable Interface
public class Country implements Comparable<Country>
{
int area;
public Country(int area)
{
this.area = area;
}
public int compareTo(Country otherCountry)
{
if (this.area < otherCountry.area) { return -1; }
else if (this.area == otherCountry.area) { return 0; }
else { return 1; }
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
86
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
87
Programming Question
 Copy and Save program SetDemo3.java
 Modify given Employee class to implement Comparable interface.
• Implement compareTo method to compare based on employee id.
SetDemo3.java
import java.util.Set;
import java.util.TreeSet;
import java.util.HashSet;
public class SetDemo3 {
public static void main(String args[]) {
Set<Employee> s = new TreeSet<Employee>();
// Add elements to the tree set
s.add(new Employee("Jim", 1));
s.add(new Employee("Andy", 2));
s.add(new Employee("Brandon", 4));
s.add(new Employee("Sam", 3));
System.out.println(s);
Employee.java
public class Employee {
private String name;
private int id;
public Employee(String name,int id){
this.name = name;
this.id = id;
}
public String toString(){
return "[Employee:name="+name+"
id="+id+"]";
}
}
}
}
Output:
[[Employee: name=Jim id=1], [Employee: name=Andy id=2], [Employee: name=Sam id=3], [Employee: name=Brandon id=4]]
Copyright © 2014 by John Wiley & Sons. All rights reserved.
88
Answer
Employee.java
public class Employee implements Comparable<Employee> {
private String name;
private int id;
public Employee(String name,int id){
this.name = name;
this.id = id;
}
public int compareTo(Employee other) {
if (id < other.id) { return -1; }
else if (id == other.id) { return 0; }
else { return 1; }
}
public String toString(){
return "[Employee: name="+name+" id="+id+"]";
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
89
Homework: Programming Question
 Modify compareTo to compare based on employee name
Output:
[[Employee: name=Andy id=2], [Employee: name=Brandon id=4], [Employee: name=Jim id=1], [Employee: name=Sam id=3]]
Copyright © 2014 by John Wiley & Sons. All rights reserved.
90
Answer
public class Employee implements Comparable<Employee> {
private String name;
private int id;
public Employee(String name,int id){
this.name = name;
this.id = id;
}
public int compareTo(Employee other) {
return name.compareTo(other.name);
}
public String toString(){
return "[Employee: name="+name+" id="+id+"]";
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
91
3. 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.
92
 Example map (set of <key, value> pairs )
Copyright © 2014 by John Wiley & Sons. All rights reserved.
93
Browse project specification (PHASE2)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
94
 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.
95
Copyright © 2014 by John Wiley & Sons. All rights reserved.
96
 Some predefined Java classes that implement the notion
of a dictionary are:
• HashMap
• TreeMap
• The TreeMap 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.
97
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.
 No duplicate keys allowed
Figure 10 A Map
Copyright © 2014 by John Wiley & Sons. All rights reserved.
98
Maps
 Store the reference to the map object in a Map reference:
Map<String, Color> favoriteColors = new HashMap<String, Color>();
Map<String, Color> favoriteColors = new TreeMap<String, Color>();
Key type
Key represent Person Name
Value type
Value represent favorite color of person
Copyright © 2014 by John Wiley & Sons. All rights reserved.
99
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
100
Maps
Map<String, Color> favoriteColors = new HashMap<String, Color>();
Map<String, Color> favoriteColors = new TreeMap<String, Color>();
 Use the put method to add an association/ a <key,value> pair :
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 a <key,value> pair, call the remove method with the key:
favoriteColors.remove("Juliet");
Copyright © 2014 by John Wiley & Sons. All rights reserved.
101
Working with Maps
Copyright © 2014 by John Wiley & Sons. All rights reserved.
102
Maps
 The keySet method yields the set of keys.
 To iterate through <key,value> pairs in a map m:
Set<String> keySet = m.keySet(); //get set of keys
for (String key : keySet)//for each key
{
Color value = m.get(key); //get value associated with key
System.out.println(key + "->" + value); //print key,value pair
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
103
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
104
Programming Question
 Implement the tester class MapDemo. In the main method, create a
map called favoriteColors with person name as the key (String) and
favorite color of the person as value (Color). 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.
105
Answer
import
import
import
import
import
MapDemo.java
java.awt.Color;
java.util.HashMap;
java.util.TreehMap;
java.util.Map;
java.util.Set;
public class MapDemo
{
public static void main(String[] args)
{
Map<String, Color> favoriteColors = new HashMap<String, Color>();
favoriteColors.put("Juliet", Color.BLUE);
favoriteColors.put("Romeo", Color.GREEN);
favoriteColors.put("Adam", Color.RED);
favoriteColors.put("Eve", Color.BLUE);
// Print all keys and values in the map
Set<String> keySet = favoriteColors.keySet();
for (String key : keySet)
{
Color value = favoriteColors.get(key);
System.out.println(key + " : " + value);
}
}
}
How does the output change if you change HashMap to TreeMap?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
106
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.
107
Answer
Answer:
Map<String, Integer> wordFrequency;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
108
Question
 Suppose you want to maintain a thesaurus that lists
synonyms for a given word as a collection.
 For example, the key "improve" might have as its
synonyms: ["ameliorate", "better", "enhance",
"enrich", "perfect", "refine"].
 How do we define a suitable collection for this?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
109
Answer
Map<String, HashSet<String>>
word
synonyms
Copyright © 2014 by John Wiley & Sons. All rights reserved.
110
Programming Question
 Write a program WordCount to read a text file (poem.txt) and print
count of each word in the text. Use a map to keep track of count of
each word.
poem.txt
 Sample output:
We were stepping out of a reading
in October, the first cold night,
and we were following this couple,
were they at the reading? and because
we were lost, I called out to them,
“Are you going to the after party?”
The woman laughed and said no
and the man kept walking, and she
was holding his hand like I hold yours,
though not exactly, she did not
need him for balance. Then what
got into me? I said, “How long
have you been married?” and she said
“Almost 30 years” and because
we were walking in public, no secret,
tell everyone now it’s official,
I said, “How’s marriage?” The man
kept walking. The woman said,
“It gets better but then it gets different.”
The man kept walking.
Find program
template in next
slide
Create and save poem.txt
with above content
Copyright © 2014 by John Wiley & Sons. All rights reserved.
111
import java.util.*;
import java.io.*;
public class WordCount {
public static void main(String args[]) throws IOException {
//TODO: create map : wordFrequency
//create a scanner object to read file
Scanner sc = new Scanner(new File("poem.txt"));
sc.useDelimiter("[^a-zA-Z]+"); // Use any characters other than a-z or A-Z as delimiters
//TODO: update count of words in map
//TODO: print map (word along with its frequency)
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
112
Answer
WordCount.java
import java.util.*;
import java.io.*;
public class WordCount {
public static void main(String args[]) throws IOException {
//create map: key=word, value=count of word
Map<String, Integer> wordFrequency = new HashMap<String, Integer>();
//create a scanner object to read file
Scanner sc = new Scanner(new File("poem.txt"));
sc.useDelimiter("[^a-zA-Z]+");
//update count of words in map
while (sc.hasNext()) {
String word = sc.next();
if (wordFrequency.get(word) != null) {
int count = wordFrequency.get(word);
count++;
wordFrequency.put(word, count);
}
else {
wordFrequency.put(word, 1);
}
}
//print map (word along with its frequency)
//System.out.println("wordFrequency: " + wordFrequency);
Set<String> keySet = wordFrequency.keySet();
for (String key : keySet)
{
Integer value = wordFrequency.get(key);
System.out.println(key + " : " + value);
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
113
Stacks
 A stack lets you insert and remove elements only at one end(top):
• Last-in, first-out or LIFO order
• Removes items in the opposite order than they were added
 Add and remove methods are called push and pop.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
114
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.
115
Stacks
 Example
Stack<String> s = new Stack<String>();
s.push("A");
s.push("B");
s.push("C");
System.out.print(s.pop()); // Prints C
Copyright © 2014 by John Wiley & Sons. All rights reserved.
116
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
117
 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.
118
Stacks
 Many applications for stacks in computer science.
 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.
119
Programming Question
 Implement a tester class 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.
120
Answer
StackDemo.java
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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
121
Programming Question
Printing a Sentence in Reverse Using a Stack:
Write a program StackDemo2.java that takes a line of text and uses
a stack to display the words of the line in reverse order.
For example, given the string= “My name is Tom” output is “Tom is
name My”:
Find program
template in next
slide
Copyright © 2014 by John Wiley & Sons. All rights reserved.
122
public class StackDemo2
{
public static void main( String[] args )
{
//TODO: create stack
// get input sentence
Scanner scanner = new Scanner( "My name is Tom" );
//TODO: take each word from input and push on stack
//TODO: print reverse string by popping words from stack.
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
123
Answer
StackDemo2.java
import java.util.Scanner;
import java.util.Stack;
public class StackDemo2
{
public static void main( String[] args )
{
//create stack
Stack< String > stack = new Stack< String >();
// get input text
Scanner scanner = new Scanner( "My name is Tom" );
// take each word from input and push on stack
while ( scanner.hasNext())
{
stack.push( scanner.next() );
//System.out.println("st="+stack);
}
System.out.println( "Input string in reverse order:" );
// build reverse string by popping words from stack.
while ( !stack.isEmpty() )
{
Object removedObject = stack.pop();
System.out.printf( "%s ", removedObject );
} // end while
System.out.println(); // print trailing newline
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
124
References
 From : Beginning Java Objects, JACQUIE BARKER
Copyright © 2014 by John Wiley & Sons. All rights reserved.
125