copyright © 2014 by john wiley & sons. all rights reserved.1 the java collections framework

120
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 The Java Collections Framework

Upload: georgia-freeman

Post on 16-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Copyright © 2014 by John Wiley & Sons. All rights reserved. 1

The Java Collections Framework

Copyright © 2014 by John Wiley & Sons. All rights reserved. 2

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.

1. 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

2. We do not know until runtime how many objects to create

– So we can’t predefine no. of reference variables at compile time

– Most collection needn’t be assigned an explicit capacity at the time that they are instantiated

– Collections can grow and shrink as needed.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 3

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!

Copyright © 2014 by John Wiley & Sons. All rights reserved. 4

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. 5

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. 6

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. 7

Copyright © 2014 by John Wiley & Sons. All rights reserved. 8

Copyright © 2014 by John Wiley & Sons. All rights reserved. 9

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. 10

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

• By default, items are added at the end of an ordered list

• 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. 11

List Interface Implementations ArrayList - FIFO

• low cost random access

• high cost insert and delete

• array that resizes if need be

LinkedList

• sequential access

• low cost insert and delete

• high cost random access

Stack• LIFO

Vector

Copyright © 2014 by John Wiley & Sons. All rights reserved. 12

Interface List

Copyright © 2014 by John Wiley & Sons. All rights reserved. 13

ArrayList Resizable-array implementation of the List interface.

To declare an array list of strings

ArrayList<String> names = new ArrayList<String>();

Angle brackets denote a type parameter

• Replace String with any other class to get a different array list type

• E.g.

ArrayList<Student> waitinglist = new ArrayList<Student>();

Refer javadoc API ArrayList class page

Copyright © 2014 by John Wiley & Sons. All rights reserved. 14

Declaring and Using Array Lists ArrayList<String> is first constructed, it has size 0:

ArrayList<String> names = new ArrayList<String>();

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”

The size method gives the current size of the array list.

• Size is now 3

Figure 17 Adding an Array List Element with add

Copyright © 2014 by John Wiley & Sons. All rights reserved. 15

Array Lists

Refer javadoc API ArrayList class page

Copyright © 2014 by John Wiley & Sons. All rights reserved. 16

Declaring and Using Array Lists

To obtain an array list element, use the get method

• E.g. To retrieve the name with index 0:

String name = names.get(0);

The last valid index is:

names.size() - 1

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. 17

Declaring and Using Array Lists

Figure 18 Adding and Removing Elements in the Middle of an Array List

Copyright © 2014 by John Wiley & Sons. All rights reserved. 18

Declaring and Using Array Lists

The remove method,

• removes the element at a given position

• moves all elements after the removed element down by one position

• and reduces the size of the array list by 1.

names.remove(1);

Copyright © 2014 by John Wiley & Sons. All rights reserved. 19

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. Template for ArrayListDemo is given:

A sample run is sown below:

Itisabeautifulday

words.txtpublic class ArrayListDemo{ public static void main(String args[]) throws Exception { //TODO }}

ArrayListDemo.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 20

Answerimport 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){

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

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. 23

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);

Read: Deep copy vs shallow copy

Copyright © 2014 by John Wiley & Sons. All rights reserved. 24

Working With Array Lists

Copyright © 2014 by John Wiley & Sons. All rights reserved. 25

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. 26

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. 27

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. 28

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.How do you correct previous code?

Copyright © 2014 by John Wiley & Sons. All rights reserved. 29

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. 30

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. 31

Choosing Between Array Lists and Arrays

Copyright © 2014 by John Wiley & Sons. All rights reserved. 32

Programming Question

Write ArrayListDemo2 class to use an ArrayList called 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 Q3580115 <== largest value44.5

Find template in next slide:

Copyright © 2014 by John Wiley & Sons. All rights reserved. 33

public class ArrayListDemo2{ public static void main(String[] args) { //declare arraylist values // Read inputs to values

// Find the largest // Print all values, marking the largest }}

Use following template to get started:

Copyright © 2014 by John Wiley & Sons. All rights reserved. 34

Answerimport 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(); } }}

ArrayListDemo2.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 35

Question

What does the array list names contain after the following statements execute?

ArrayList<String> names = new ArrayList<String>;

names.add("Bob");

names.add(0, "Ann");

names.remove(1);

names.add("Cal");

Copyright © 2014 by John Wiley & Sons. All rights reserved. 36

Answer

Answer: "Ann", "Cal"

What does the array list names contain after the following statements?

ArrayList<String> names = new ArrayList<String>;

names.add("Bob");

names.add(0, "Ann");

names.remove(1);

names.add("Cal");

Copyright © 2014 by John Wiley & Sons. All rights reserved. 37

Linked Lists Doubly-linked list implementation of the List interface.

A linked list consists of a number of nodes

Each node stores element + has 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. 38

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. 39

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. 40

The LinkedList Class of the Java Collections Framework

Generic class

• Specify type of elements in angle brackets:

LinkedList<Product> l= new LinkedList<Product>();

LinkedList<Integer> l= new LinkedList<Integer>();

Some methods:

l.add("C");

l.addLast("Z"); //add as last element

l.addFirst("A"); //add as first element

l.add("B",3);

l.remove(2);

l.removeFirst(); //remove first element

ll.removeLast(); //remove last element

Copyright © 2014 by John Wiley & Sons. All rights reserved. 41

The LinkedList Class of the Java Collections Framework

Some additional LinkedList methods:

Refer javadoc api

Copyright © 2014 by John Wiley & Sons. All rights reserved. 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();

Copyright © 2014 by John Wiley & Sons. All rights reserved. 43

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(); //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. 44

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 in ListIterator:

• hasNext

• next - return next element and moves the iterator position past it

To move the list position backwards, use methods in ListIterator :

• hasPrevious

• Previous - return previous element and moves the iterator position past it

Copyright © 2014 by John Wiley & Sons. All rights reserved. 45

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"); ListIterator<String> iterator = l.listIterator(); // |ABC while (iterator.hasNext()) { String name = iterator.next(); // A|BC AB|C ABC| System.out.println(name); }

//TODO: how to iterate list backward? }}

Copyright © 2014 by John Wiley & Sons. All rights reserved. 46

List Iterator iterator points between two elements:

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

iterator.next()

iterator.add(“J”)

Copyright © 2014 by John Wiley & Sons. All rights reserved. 47

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. 48

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. 49

Programming Question

Write a tester class LinkedListDemo 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 stafflist

• 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. 50

public class LinkedListDemo { 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. 51

Answer 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"); // | 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]"); } }

LinkedListDemo.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 52

Programming Question

Write LinkedListDemo2 class by writing a loop that removes all names with length less than 5 from staff list. (Hint: 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. 53

Answerimport 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"); 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); }}

LinkedListDemo.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 54

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. 55

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. 56

Queue

Copyright © 2014 by John Wiley & Sons. All rights reserved. 57

Queue Animator:

• Queues: Array Implementation

• Queues: Linked List Implementation

Copyright © 2014 by John Wiley & Sons. All rights reserved. 58

QuestionWhy would you want to declare a variable as

Queue<String> q = new LinkedList<String>();

instead of simply declaring it as a linked list?

Copyright © 2014 by John Wiley & Sons. All rights reserved. 59

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. 60

2. 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

• Inserting and removing elements is more efficient with a set than with a list.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 61

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. 62

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. 63

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. 64

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. 65

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. 66

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. 67

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.

• HashSet<String> set1 = new HashSet<String>();

• Set<Rectangle> set2 = new HashSet<Rectangle>();

• HashSet<HashSet<Integer>> = new HashSet<HashSet<Integer>>();

Copyright © 2014 by John Wiley & Sons. All rights reserved. 68

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

Copyright © 2014 by John Wiley & Sons. All rights reserved. 69

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. 70

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. 71

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. 72

Working with Sets

Copyright © 2014 by John Wiley & Sons. All rights reserved. 73

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, and an array of String a2 as arguments, find two sets s1 and s2 formed from list1 and a2 , 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”], a2 ={“Jim”, “Harry”, “Diana”}):

Find program template in next slide

> run SetDemos1 = [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. 74

public class SetDemo{ public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Diana"); list.add("Harry"); list.add("Romeo"); list.add("Tom"); String[] ary = {"Diana", "Harry", "Jim"}; solve(list, ary); } public static void solve(List<String> list1, String[]a2) { //TODO: create set s1 from list1 // TODO: create set s2 from a2 // TODO: create and print 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. 75

Answerimport java.util.Set;import java.util.List;import java.util.ArrayList;import java.util.HashSet;import java.util.Arrays;

public class SetDemo{ public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Harry "); list.add(" Diana "); list.add("Romeo"); list.add("Tom"); String[] ary = {"Diana", "Harry", "Jim"}; solve(list, ary); } public static void solve(List<String> list1, String[]a2) { Set<String> s1 = new HashSet<String>(list1) ; Set<String> s2 = new HashSet<String>( Arrays.asList(a2) ) ; //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); }}

SetDemo.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 76

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. 77

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?

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); }}

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+"]"; }}

SetDemo3.java Employee.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 78

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. 79

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. 80

Example class implementing Comparable Interface

public class Country implements Comparable<Country>{

int 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. 81

Programming Question Write and Save program SerDemo3.java

Modify given Employee class to implement Comparable interface. Implement compareTo method to compare based on employee id.

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); }}

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+"]"; }}

SetDemo3.java Employee.java

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. 82

Answerpublic 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+"]"; }}

Employee.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 83

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. 84

Answerpublic 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. 85

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. 86

Example map (set of <key, value> pairs )

Copyright © 2014 by John Wiley & Sons. All rights reserved. 87

Browse project specification for maps

Copyright © 2014 by John Wiley & Sons. All rights reserved. 88

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. 89

Copyright © 2014 by John Wiley & Sons. All rights reserved. 90

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. 91

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. 92

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 typeKey represent Person Name

Value typeValue represent favorite color of person

Copyright © 2014 by John Wiley & Sons. All rights reserved. 93

Copyright © 2014 by John Wiley & Sons. All rights reserved. 94

Maps 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. 95

Working with Maps

Copyright © 2014 by John Wiley & Sons. All rights reserved. 96

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 keysfor (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. 97

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. 98

Answerimport java.awt.Color;import java.util.HashMap;import java.util.TreehMap;import java.util.Map;import 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); } }}

MapDemo.java

How does the output change if you change HashMap to TreeMap?

Copyright © 2014 by John Wiley & Sons. All rights reserved. 99

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. 100

Answer

The ordering does not matter, and you cannot have duplicates

Copyright © 2014 by John Wiley & Sons. All rights reserved. 101

Question

Why is the collection of the values of a map not a set?

Copyright © 2014 by John Wiley & Sons. All rights reserved. 102

Answer

Because it might have duplicates.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 103

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. 104

Answer

Answer:Map<String, Integer> wordFrequency;

Copyright © 2014 by John Wiley & Sons. All rights reserved. 105

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. 106

Answer

Map<String, HashSet<String>>

word synonyms

Copyright © 2014 by John Wiley & Sons. All rights reserved. 107

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.

Sample output:We were stepping out of a readingin October, the first cold night,and we were following this couple,were they at the reading? and becausewe were lost, I called out to them,“Are you going to the after party?”The woman laughed and said noand the man kept walking, and shewas holding his hand like I hold yours,though not exactly, she did notneed him for balance. Then whatgot into me? I said, “How longhave you been married?” and she said“Almost 30 years” and becausewe were walking in public, no secret,tell everyone now it’s official,I said, “How’s marriage?” The mankept walking. The woman said,“It gets better but then it gets different.”The man kept walking.

poem.txt

Create and save poem.txt with above content

Find program template in next slide

Copyright © 2014 by John Wiley & Sons. All rights reserved. 108

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. 109

Answerimport 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); } }}

WordCount.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 110

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. 111

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. 112

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. 113

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. 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

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. 116

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. 117

Programming QuestionPrinting 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. 118

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. 119

Answerimport 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 }}

StackDemo2.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. 120

References From : Beginning Java Objects, JACQUIE BARKER