Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 The Java Collections Framework."— Presentation transcript:

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

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

3 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!

4 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 An ArrayList Object

5 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

6 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

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

8 8

9 9  Three Generic Types of Collection: 1.Ordered lists 2.Dictionaries 3.Sets Ordered Lists Sets Dictionaries/Maps

10 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

11 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

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

13 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 names = new ArrayList ();  Angle brackets denote a type parameter Replace String with any other class to get a different array list type E.g. ArrayList waitinglist = new ArrayList (); Refer javadoc API ArrayList class page

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Declaring and Using Array Lists  ArrayList is first constructed, it has size 0: ArrayList names = new ArrayList ();  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

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Array Lists Refer javadoc API ArrayList class page

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

17 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

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

19 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: It is a beautiful day words.txt public class ArrayListDemo{ public static void main(String args[]) throws Exception { //TODO } ArrayListDemo.java

20 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 allWords = new ArrayList (); 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)+","); } }

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

22 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 friends = names; friends.add("Harry"); Figure 19 Copying an Array List Reference

23 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 newNames = new ArrayList (names);  Read: Deep copy vs shallow copy

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Working With Array Lists

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

26 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 inputs = new ArrayList (); while (in.hasNextDouble()) { inputs.add(in.nextDouble()); }

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Question  Removing Matches: ArrayList 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?

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

29 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++; } }

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

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Choosing Between Array Lists and Arrays

32 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: Q <== largest value 44.5 Find template in next slide:

33 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:

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Answer import java.util.ArrayList; import java.util.Scanner; public class ArrayListDemo2 { public static void main(String[] args) { //create arraylist ArrayList values = new ArrayList (); // 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

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Question What does the array list names contain after the following statements execute? ArrayList names = new ArrayList ; names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal");

36 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 names = new ArrayList ; names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal");

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

38 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”

39 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

40 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 l= new LinkedList ();  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

41 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

42 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 employeeNames = new LinkedList (); ListIterator iterator = employeeNames.listIterator();

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

44 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

45 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 l = new LinkedList (); l.add("A"); l.add("B"); l.add("C"); ListIterator 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? }

46 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”)

47 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

48 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

49 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

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

51 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 staff = new LinkedList (); staff.addLast("Diana"); staff.addLast("Harry"); staff.addLast("Romeo"); staff.addLast("Tom"); // | in the comments indicates the iterator position ListIterator 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

52 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 staff = new LinkedList (); 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); }

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Answer import java.util.LinkedList; import java.util.ListIterator; public class LinkedListDemo2 { public static void main(String[] args) { LinkedList staff = new LinkedList (); staff.addLast("Diana"); staff.addLast("Harry"); staff.addLast("Romeo"); staff.addLast("Tom"); System.out.println("list before:"+staff); ListIterator 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

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

55 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 q = new LinkedList (); q.add("A"); q.add("B"); q.add("C"); while (q.size() > 0) { System.out.print(q.remove() + " "); } // Prints A B C

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

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57  Queue Animator: Queues: Array Implementation Queues: Linked List Implementation

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Question Why would you want to declare a variable as Queue q = new LinkedList (); instead of simply declaring it as a linked list?

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

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

61 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?

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

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

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

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

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

67 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 set1 = new HashSet (); Set set2 = new HashSet (); HashSet > = new HashSet >();

68 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

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Sets  Store the reference to a TreeSet or HashSet in a Set variable: Set names = new HashSet (); Or Set names = new TreeSet ();

70 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

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

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72 Working with Sets

73 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 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 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]

74 Copyright © 2014 by John Wiley & Sons. All rights reserved.74 public class SetDemo{ public static void main(String[] args) { List list = new ArrayList (); 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 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). }

75 Copyright © 2014 by John Wiley & Sons. All rights reserved.75 Answer import 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 list = new ArrayList (); 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 list1, String[]a2) { Set s1 = new HashSet (list1) ; Set s2 = new HashSet ( Arrays.asList(a2) ) ; //s3 = s1 union s2 Set s3 = new HashSet (s1); s3.addAll(s2); System.out.println("s1 union s2 = "+s3); //s4 = s1 intersection s2 Set s4 = new HashSet (s1); s4.retainAll(s2); System.out.println("s1 intersection s2 = "+s4); //s5 = ( s1 – s2 )union (s2–s1). Set s1Subs2= new HashSet (s1); //s1-s2 s1Subs2.removeAll(s2); Set s2Subs1 = new HashSet (s2); //s2-s1 s2Subs1.removeAll(s1); Set s5= new HashSet (); s5.addAll(s1Subs2 ); s5.addAll(s2Subs1 ); System.out.println("( s1 – s2 )union (s2–s1) = "+s5); } SetDemo.java

76 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 s = new HashSet (); 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(); }

77 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 s = new TreeSet (); // 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.javaEmployee.java

78 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

79 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

80 Copyright © 2014 by John Wiley & Sons. All rights reserved.80  Example class implementing Comparable Interface public class Country implements Comparable { 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; } }

81 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 s = new TreeSet (); // 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.javaEmployee.java Output: [[Employee: name=Jim id=1], [Employee: name=Andy id=2], [Employee: name=Sam id=3], [Employee: name=Brandon id=4]]

82 Copyright © 2014 by John Wiley & Sons. All rights reserved.82 Answer public class Employee implements Comparable { 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

83 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]]

84 Copyright © 2014 by John Wiley & Sons. All rights reserved.84 Answer public class Employee implements Comparable { 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+"]"; }

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

86 Copyright © 2014 by John Wiley & Sons. All rights reserved.86  Example map (set of pairs )

87 Copyright © 2014 by John Wiley & Sons. All rights reserved.87 Browse project specification for maps

88 Copyright © 2014 by John Wiley & Sons. All rights reserved.88  Maps are realized in java using Map interface Set of 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

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

90 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 timenatural ordering of its keysComparator guaranteed log(n) time cost for the containsKey, get, put and remove operations

91 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

92 Copyright © 2014 by John Wiley & Sons. All rights reserved.92 Maps  Store the reference to the map object in a Map reference: Map favoriteColors = new HashMap (); Map favoriteColors = new TreeMap (); Key type Key represent Person Name Value type Value represent favorite color of person

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

94 Copyright © 2014 by John Wiley & Sons. All rights reserved.94 Maps  Use the put method to add an association/ a 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 pair, call the remove method with the key: favoriteColors.remove("Juliet");

95 Copyright © 2014 by John Wiley & Sons. All rights reserved.95 Working with Maps

96 Copyright © 2014 by John Wiley & Sons. All rights reserved.96 Maps  The keySet method yields the set of keys.  To iterate through pairs in a map m: Set 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 }

97 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 pairs based on following diagram:  Finally print all 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]

98 Copyright © 2014 by John Wiley & Sons. All rights reserved.98 Answer import 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 favoriteColors = new HashMap (); 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 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?

99 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?

100 Copyright © 2014 by John Wiley & Sons. All rights reserved.100 Answer The ordering does not matter, and you cannot have duplicates

101 Copyright © 2014 by John Wiley & Sons. All rights reserved.101 Question Why is the collection of the values of a map not a set?

102 Copyright © 2014 by John Wiley & Sons. All rights reserved.102 Answer Because it might have duplicates.

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

104 Copyright © 2014 by John Wiley & Sons. All rights reserved.104 Answer Answer: Map wordFrequency;

105 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?

106 Copyright © 2014 by John Wiley & Sons. All rights reserved.106 Answer Map > word synonyms

107 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 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. poem.txt Create and save poem.txt with above content Find program template in next slide

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

109 Copyright © 2014 by John Wiley & Sons. All rights reserved.109 Answer 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 wordFrequency = new HashMap (); //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 keySet = wordFrequency.keySet(); for (String key : keySet) { Integer value = wordFrequency.get(key); System.out.println(key + " : " + value); } } WordCount.java

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

111 Copyright © 2014 by John Wiley & Sons. All rights reserved.111 Stacks  Example Stack s = new Stack (); s.push("A"); s.push("B"); s.push("C"); System.out.print(s.pop()); // Prints C

112 Copyright © 2014 by John Wiley & Sons. All rights reserved.112  Stack Animator: Array implementation: List Implementation:

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

114 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

115 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:

116 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 st = new Stack (); // 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

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

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

119 Copyright © 2014 by John Wiley & Sons. All rights reserved.119 Answer import java.util.Scanner; import java.util.Stack; public class StackDemo2 { public static void main( String[] args ) { //create stack Stack stack = new Stack (); // 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

120 Copyright © 2014 by John Wiley & Sons. All rights reserved.120 References  From : Beginning Java Objects, JACQUIE BARKER


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

Similar presentations


Ads by Google