Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Overview of the Collections Framework

Similar presentations


Presentation on theme: "An Overview of the Collections Framework"— Presentation transcript:

1

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. At other times, individualized reference variables are impractical. Too large no. of objects to create: E.g. university course catalog might have hundreds of courses We do not know until runtime how many objects to create So we can’t predefine no. of reference variables at compile time Most collection needn’t be assigned an explicit capacity at the time that they are instantiated Collections can grow and shrink as needed.

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 A collection organizes references to objects that live in memory outside of the collection:
BankAccount Object BankAccount Object BankAccount Object An ArrayList Object

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

8

9 Three Generic Types of Collection:
Ordered lists Dictionaries Sets Ordered Lists Sets Dictionaries/Maps

10 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 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 Interface List

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

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

15 Array Lists Refer javadoc API ArrayList class page

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 Declaring and Using Array Lists
Figure 18 Adding and Removing Elements in the Middle of an Array List

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 Programming Question Write a tester class ArrayListDemo to display the words of a file (words.txt) as a list: Read file content to an arrayList allWords Hint: Use Scanner class: Scanner input = new Scanner(new File("words.txt")); Print elements in allWords 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: words.txt ArrayListDemo.java It is a beautiful day public class ArrayListDemo{ public static void main(String args[]) throws Exception { //TODO }

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)+",");

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

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

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 Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

24 Working With Array Lists

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

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()); } > run LinkedListDemo2 list before:[Diana, Harry, Romeo, Tom] list after:[Diana, Harry, Romeo] > import java.util.* > Collection<Integer> c = new ArrayList<Integer>() > c.add(1); > List<Integer> c = new ArrayList<Integer>() >

27 Question Removing Matches: What is the purpose of the code?
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?

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 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 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 Choosing Between Array Lists and Arrays

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 35 80 115 <== largest value 44.5 Find template in next slide:

33 Use following template to get started:
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 }

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

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

36 Answer 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"); Answer: "Ann", "Cal"

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 Linked Lists When inserting/adding or removing a node:
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 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 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

41 The LinkedList Class of the Java Collections Framework
Some additional LinkedList methods: Refer javadoc api

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

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) foreach loop uses an Iterator behind the scenes

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 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? 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(); while (iterator.hasNext()) String name = iterator.next(); System.out.println(name); } while (iterator.hasPrevious()) //if you comment previous while loop,this while loop will not print anything String name = iterator.previous();

46 List Iterator adds an object after the 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 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 List Iterator Refer javadoc api
ListIterator interface extends Iterator interface. Methods of the Iterator and ListIterator interfaces Refer javadoc api

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 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 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"); // | 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]"); } iterator.next(); // DHJNR|T //comment this line to see IllegalStateException // Remove last traversed element iterator.remove(); // DHJN|T

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

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

54 Queue A queue To visualize a queue, think of people lining up.
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 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

56 Queue

57 Queue Animator: Queues: Array Implementation
Queues: Linked List Implementation

58 Question Why would you want to declare a variable as Queue<String> q = new LinkedList<String>(); instead of simply declaring it as a linked list?

59 Answer This way, we can ensure that only queue operations can be invoked on the q object.

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.

61 Question A gradebook application stores a collection of quizzes. Should it use a list or a set?

62 Answer A list is a better choice because the application will want to retain the order in which the quizzes were given.

63 Question A student information system stores a collection of student records for a university. Should it use a list or a set?

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 Set Realized using Set interface Question: Refer javadoc api
What are classes implementing Set interface? (use java API to find out)

66 Sets Two implementing classes :
HashSet based on hash table TreeSet based on binary search tree A Set implementation arranges the elements so that it can locate them quickly.

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>>(); HashMap LoadFactor: An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. In Java, every class provides a hashCode() method, which digests the data stored in an instance of the class into a single hash value (a 32-bit signed integer). 2 ~]$ echo -n 'text to be encrypted' | md5sum - 8df639b301a1e10c36cc2f03bbdf8863 5 ~]$ echo -n 'text to be encrypt' | md5sum - a57f7943d c75598fce8dbb2da -

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 It is a bit more efficient — if the hash function is well chosen public class BankAccount implements Comparable<BankAccount>  {      . . .      /**          Compares two bank accounts.      */      public int compareTo(BankAccount other) { if (balance < other.balance) return -1; if (balance == other.balance) return 0; return 1; }     private double balance;  }

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

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

72 Working with Sets

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”}): > 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] Find program template in next slide

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

75 Answer SetDemo.java 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<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);

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

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? SetDemo3.java Employee.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+"]";

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

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. SetDemo3.java Employee.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+"]"; Output: [[Employee: name=Jim id=1], [Employee: name=Andy id=2], [Employee: name=Sam id=3], [Employee: name=Brandon id=4]]

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

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

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.

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

87 Browse project specification for maps

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

89

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

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

93

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

95 Working with Maps

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

98 Answer MapDemo.java 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<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?

99 Question Why is the collection of the keys of a map a set and not a list?

100 Answer The ordering does not matter, and you cannot have duplicates

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

102 Answer Because it might have duplicates.

103 Question Suppose you want to track how many times each word occurs in a document. Declare a suitable map variable.

104 Answer Answer: Map<String, Integer> wordFrequency;

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 Answer Map<String, HashSet<String>> word synonyms

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: poem.txt 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

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

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 Stacks Example Stack<String> s = new Stack<String>();
s.push("A"); s.push("B"); s.push("C"); System.out.print(s.pop()); // Prints C

112 Stack Animator: Array implementation: List Implementation:
List Implementation:

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 Stack in the Java Library
Stack class provides push, pop and peek methods. Refer javadoc api

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

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

120 References From : Beginning Java Objects, JACQUIE BARKER


Download ppt "An Overview of the Collections Framework"

Similar presentations


Ads by Google