Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 22 Java Collections Framework CIS265/506 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive.

Similar presentations


Presentation on theme: "Chapter 22 Java Collections Framework CIS265/506 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive."— Presentation transcript:

1 Chapter 22 Java Collections Framework CIS265/506 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition by Y. Daniel Liang

2 Java Collection Framework hierarchy 2 A collection is a container object that represents a group of objects, often referred to as elements. The Java Collections Framework supports three types of collections, named sets, lists, and maps.

3 Java Collection Framework hierarchy, cont. 3 A collection is a container that stores objects.

4 Java Collection Framework hierarchy, cont. 4 An instance of Map represents a group of objects, each of which is associated with a key. You can get the object from a map using a key, and you have to use a key to put the object into the map.

5 The Collection Interface 5 The Collection interface is the root interface for manipulating a collection of objects.

6 The Set Interface 6 The Set interface extends the Collection interface. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements. The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is, two elements e1 and e2 can be in the set, if and only if e1.equals(e2) is false.

7 The Set Interface Hierarchy 7

8 The AbstractSet Class 8 The AbstractSet class is a convenience class that extends AbstractCollection and implements Set. The AbstractSet class provides concrete implementations for the equals method and the hashCode method. The hash code of a set is the sum of the hash code of all the elements in the set. Since the size method and iterator method are not implemented in the AbstractSet class, AbstractSet is an abstract class.

9 The HashSet Class 9 The HashSet class is a concrete class that implements Set. It can be used to store duplicate-free elements. For efficiency, objects added to a hash-set need to implement the hashCode method in a manner that properly disperses their hash code ( hashCode is originally defined in the Object class) The hashCode value is used as a pseudo-key. The hash codes of two objects must be the same if the two objects are equal. Two unequal objects may have the same hash code, but you should implement the hashCode method to avoid too many of such cases (collisions). Most of the classes in the Java API implement the hashCode method. For example: The hashCode in the Integer class returns its int value. The hashCode in the Character class returns the Unicode of the character. The hashCode in the String class returns: s 0 * 31 (n-1) + s 1 *31 (n-2) + … + s n-1 where s i is s.charAt(i).

10 Example: Using HashSet and Iterator 10 This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list. public class TestHashSet { public static void main(String[] args) { // Create a hash set Set set = new HashSet (); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println( set ); // Obtain an iterator for the hash set Iterator iterator = set.iterator(); // Display the elements in the hash set while (iterator.hasNext()) { System.out.print(iterator.next().toUpperCase() + " "); } [San Francisco, New York, Paris, Beijing, London] SAN FRANCISCO NEW YORK PARIS BEIJING LONDON

11 TIP: for-each loop 11 Instead of defining and using an Iterator you should use the for-each loop (results in simpler and equally efficient code) for (Object element: set) { System.out.print(element.toString() + " "); } ArrayList list = new ArrayList(Arrays.asList( 11, 22, 33, 44, 55, 66)); for (Object n : list){ System.out.println ( n ); }

12 Example: Using LinkedHashSet 12 This example creates a hash set filled with strings, and uses a for-each loop to traverse the elements in the list. public class TestLinkedHashSet { public static void main(String[] args) { // Create a hash set Set set = new LinkedHashSet (); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println(set); // Display the elements in the hash set for (Object element: set) System.out.print(element.toString().toLowerCase() + " "); } [London, Paris, New York, San Francisco, Beijing] london paris new york san francisco beijing

13 The SortedSet Interface and the TreeSet Class 13 SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order. The elements can be sorted in two ways. If you use non-primitive types you must either 1. Implement the Comparable interface and provide your version of the compareTo method, or 2. Implement the Comparator interface and supply your version of the compare and equals method.

14 Example: Using TreeSet to Sort Elements in a Set 14 1. This example creates a hash set filled with strings, and 2. then creates a (sorted) tree set for the same strings. 3. The strings are sorted in the tree set using the native compareTo method provided by Java on behave of the String class. 4. The example also creates a tree set of geometric objects. 5. The geometric objects are sorted using the compare method in the Comparator interface.

15 Example: Using TreeSet to Sort Elements in a Set 15 public class TestTreeSet { public static void main(String[] args) { // Create a hash set Set set = new HashSet (); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println("Unsorted set: \t" + set); TreeSet treeSet = new TreeSet (set); System.out.println("Sorted tree set: " + treeSet); // Use the methods in SortedSet interface System.out.println("first(): \t" + treeSet.first()); System.out.println("last(): \t" + treeSet.last()); System.out.println("headSet(): \t" + treeSet.headSet("New York")); System.out.println("tailSet(): \t" + treeSet.tailSet("New York")); // Use the methods in NavigableSet interface System.out.println("lower(\"P\"): \t“ + treeSet.lower("P")); System.out.println("higher(\"P\"): \t" + treeSet.higher("P")); System.out.println("floor(\"P\"): \t" + treeSet.floor("P")); System.out.println("ceiling(\"P\"): \t" + treeSet.ceiling("P")); System.out.println("pollFirst(): \t" + treeSet.pollFirst()); System.out.println("pollLast(): \t" + treeSet.pollLast()); System.out.println("New tree set: \t" + treeSet); }

16 Example: Using TreeSet to Sort Elements in a Set 16 Console Unsorted set: [San Francisco, New York, Paris, Beijing, London] Sorted tree set: [Beijing, London, New York, Paris, San Francisco] first(): Beijing last(): San Francisco headSet(): [Beijing, London] tailSet(): [New York, Paris, San Francisco] lower("P"): New York higher("P"): Paris floor("P"): New York ceiling("P"): Paris pollFirst(): Beijing pollLast(): San Francisco New tree set: [London, New York, Paris] Respect to “New York”

17 The Comparator Interface 17 1. Sometimes you want to insert elements of different types into a tree set (say Circles, Triangles, Rectangles,…) 2. The elements may not be instances of Comparable or are not comparable. 3. You can define a comparator to compare these elements. 4. To do so, create a class that implements the java.util.Comparator interface. 5. The Comparator interface has two methods, compare and equals.

18 The Comparator Interface 18 public int compare(Object element1, Object element2) Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal. public boolean equals(Object element) Returns true if the specified object is also a comparator and imposes the same ordering as this comparator.

19 import java.util.Comparator; public class GeometricObjectComparator implements Comparator { public int compare(GeometricObject o1, GeometricObject o2) { double area1 = o1.getArea(); double area2 = o2.getArea(); if (area1 < area2) return -1; else if (area1 == area2) return 0; else return 1; } Example: The Using Comparator to Sort Elements in a Set 19 The example creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. 1.Alternatively you may change the class GeometricObject and ask it to implement the interface Comparable 2.TODO: Draw a hierarchy tree

20 public class TestTreeSetWithComparator { public static void main(String[] args) { // Create a tree set for geometric objects using a comparator Set set = new TreeSet ( new GeometricObjectComparator() ); set.add(new Rectangle(4, 5)); set.add(new Circle(40)); set.add(new Rectangle(4, 1)); // Display geometric objects in the tree set System.out.println("A sorted set of geometric objects"); String msg; for (GeometricObject element : set) { if (element instanceof Circle) msg = ((Circle) element).toString(); else msg = ((Rectangle) element).toString(); System.out.println("\narea = " + element.getArea() + "\n" + msg); } Example: The Using Comparator to Sort Elements in a Set 20 The example creates a sorted tree set of geometric objects.

21 Example: The Using Comparator to Sort Elements in a Set 21 The example creates a sorted tree set of geometric objects. CONSOLE A sorted set of geometric objects area = 4.0 >>> Rectangle white created on Wed Feb 08 16:01:58 EST 2012 color: white and filled: false >>> Height: 1.0 Width: 4.0 Perimeter: 10.0 Area: 4.0 area = 20.0 >>> Rectangle white created on Wed Feb 08 16:01:58 EST 2012 color: white and filled: false >>> Height: 5.0 Width: 4.0 Perimeter: 18.0 Area: 20.0 area = 5026.548245743669 >>> Circle white created on Wed Feb 08 16:01:58 EST 2012 color: white and filled: false >>> Radius: 40.0 Perimeter: 251.32741228718345 Area: 5026.548245743669

22 The List Interface 22 1. A set stores non-duplicate elements. 2. To allow duplicate elements to be stored in a collection, you need to use a list. 3. A list can not only store duplicate elements, but can also allow the user to specify where the element is stored. 4. The user can access the element by index.

23 The List Interface, cont. 23

24 The List Iterator 24

25 Array, ArrayList and LinkedList 25 1. The ArrayList class and the LinkedList class are concrete implementations of the List interface. If you need to support random access without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. If, however, your application requires the insertion or deletion of elements from any place in the list, you should choose LinkedList. 2. A list can grow or shrink dynamically. 3. An array is fixed once it is created. 4. If your application does not require insertion or deletion of elements, the most efficient data structure is the array.

26 ArrayList 26 ArrayList implements List using an array.

27 LinkedList 27 LinkedList implements List using an dynamic linked list

28 Example: Using ArrayList and LinkedList 28 This example creates an ArrayList filled with strings, then inserts, and removes elements. Finally it traverses the list in both directions. public class TestList { public static void main(String[] args) { // Create a list List list = new ArrayList (); // Add elements to the list list.add("America"); // Add it to the list System.out.println("(1) " + list); list.add(0, "Canada"); // Add it to the beginning of the list System.out.println("(2) " + list); list.add("Russia"); // Add it to the end of the list System.out.println("(3) " + list); list.add("France"); // Add it to the end of the list System.out.println("(4) " + list); list.add(2, "Germany"); // Add it to the list at index 2 System.out.println("(5) " + list); CONSOLE (1) [America] (2) [Canada, America] (3) [Canada, America, Russia] (4) [Canada, America, Russia, France] (5) [Canada, America, Germany, Russia, France]

29 Example: Using ArrayList and LinkedList 29 This example creates an ArrayList filled with strings, then inserts, and removes elements. Finally it traverses the list in both directions. list.add(5, "Norway"); // Add it to the list at index 5 System.out.println("(6) " + list); // Remove elements from the list list.remove("Canada"); // Same as list.remove(0) in this case System.out.println("(7) " + list); list.remove(2); // Remove the element at index 2 System.out.println("(8) " + list); list.remove(list.size() - 1); // Remove the last element System.out.println("(9) " + list); } CONSOLE (1) [America] (2) [Canada, America] (3) [Canada, America, Russia] (4) [Canada, America, Russia, France] (5) [Canada, America, Germany, Russia, France] (6) [Canada, America, Germany, Russia, France, Norway] (7) [America, Germany, Russia, France, Norway] (8) [America, Germany, France, Norway] (9) [America, Germany, France]

30 Performance of Sets and Lists 30 In this benchmark 50,000 integer numbers are added to a container. Later they are shuffled, and deleted from the container. The observed completion times are given below Time in milliseconds

31 The Collections Class UML Diagram 31 The Collections class contains static methods for manipulating lists and collections.

32 Example: Using the Collections Class 32 The example creates a list, sorts it, and searches for an element. public class TestCollectionMethods { public static void main(String[] args){ List list = Arrays.asList("red", "white", "blue"); Collections.sort(list); System.out.println( "1\t" + list); Collections.sort(list, Collections.reverseOrder() ); System.out.println( "2\t" + list); Collections.reverse(list); System.out.println( "3\t" + list); Collections.shuffle(list); System.out.println( "4\t" + list); List list2 = Arrays.asList("x", "y", "z"); Collections.copy(list, list2); System.out.println( "5A\t" + list); System.out.println( "5B\t" + list); System.out.println( "6\t" + Collections.max(list) ); System.out.println( "7\t" + Collections.min(list) ); System.out.println( "8\t" + Collections.frequency(list, "x") ); System.out.println( "9\t" + Collections.disjoint(list, list2) ); Collections.fill(list, "nada"); System.out.println( "10\t" + list); List list1 = Arrays.asList(2, 4, 7, 10, 11, 45, 50, 59, 60, 66); System.out.println( "11\t" + Collections.binarySearch(list1, 7) ); } CONSOLE 1[blue, red, white] 2[white, red, blue] 3[blue, red, white] 4[red, white, blue] 5A[x, y, z] 5B[x, y, z] 6z 7x 81 9false 10[nada, nada, nada] 112

33 The Vector Class 33 1.Vector is similar to ArrayList, except that Vector contains the synchronized methods for accessing and modifying data in a multithreading scenario. 2.None of the other collection data structures introduced so far are synchronized.

34 The Stack Class 34 The Stack class represents a last-in-first-out LIFO collection of objects. You can retrieve, insert, or remove an element only from the top of the stack. push pop top peek

35 Example: Using the Stack Class 35 public class TestingTheStackClass { public static void main(String[] args) { Stack stack1 = new Stack(); stack1.push("aaa"); stack1.push("bbb"); stack1.push("ccc"); stack1.push("ddd"); System.out.println( "0\t" + stack1 ); System.out.println( "1\t" + stack1.size()); System.out.println( "2\t" + stack1.peek()); System.out.println( "3\t" + stack1.contains("aaa")); System.out.println( "4\t" + stack1.get(0)); System.out.println( "5\t" + stack1.add("xxx")); System.out.println( "6\t" + stack1.indexOf("aaa")); while (!stack1.isEmpty()) { System.out.println( "7\t" + stack1.pop()); System.out.println( "8\t" + stack1 ); } For now, ignore warnings about giving the stack a data type Console 0[aaa, bbb, ccc, ddd] 14 2ddd 3true 4aaa 5true 60 7xxx 8[aaa, bbb, ccc, ddd] 7ddd 8[aaa, bbb, ccc] 7ccc 8[aaa, bbb] 7bbb 8[aaa] 7aaa 8[] 

36 peek element Queues and Priority Queues 36 1. A queue is a first-in/first-out FIFO data structure. 2. Elements are appended to the end of the queue and are removed from the beginning of the queue. 3. In a priority queue, elements are assigned priorities. 4. When accessing elements, the element with the highest priority is removed first. offer( e ) poll remove headtail

37 The Queue Interface 37

38 The PriorityQueue Class 38 1.By default, a priority queue orders its elements according to their natural ordering using Comparable. 2.The element with the least value is assigned the highest priority and thus is removed from the queue first. 3.If there are several elements with the same highest priority, the tie is broken arbitrarily. 4.You can also specify an ordering using a comparator in the constructor PriorityQueue( initialCapacity, comparator). 5.For example, the comparator obtained from Collections.reverseOrder(), could be used so the elements are removed from the queue in decreasing order.

39 The PriorityQueue Class 39 public class TestingPriorityQueue { public static void main(String[] arg) { PriorityQueue queue1 = new PriorityQueue (); queue1.offer("01-data1"); queue1.offer("02-data2"); queue1.offer("01-data3"); queue1.offer("01-data4"); queue1.offer("02-data5"); queue1.offer("01-data6"); System.out.print("\nPriority queue using default Comparator :\n Head>> "); while (queue1.size() > 0) { System.out.print(queue1.remove() + " "); } PriorityQueue queue2 = new PriorityQueue ( 4, Collections.reverseOrder() ); queue2.offer("01-data1"); queue2.offer("02-data2"); queue2.offer("01-data3"); queue2.offer("01-data4"); queue2.offer("02-data5"); queue2.offer("01-data6"); System.out.print("\nPriority queue using default Comparator :\n Head>> "); while (queue2.size() > 0) { System.out.print(queue2.remove() + " "); } CONSOLE Priority queue using default Comparable : Head>> 01-data1 01-data3 01-data4 01-data6 02-data2 02-data5 Priority queue using default Comparator : Head>> 02-data5 02-data2 01-data6 01-data4 01-data3 01-data1

40 40 The PriorityQueue Class 40 NOTE Elements in Priority Queue queue1 will be shown in an arrival/arbitrary order when issuing the Java command: System.out.println( queue1 ); However the value with the highest priority will be removed first when invoking command System.out.println( queue1.remove() ) Console (using iterator ) Priority queue using Comparable: Head>> 01-data1 01-data3 01-data4 01-data6 02-data2 02-data5 Priority queue using Comparator: Head>> 02-data5 02-data2 01-data6 01-data4 01-data3 01-data1 Console [ 01-data1, 01-data4, 01-data3, 02-data2, 02-data5, 01-data6 ]

41 The Map Interface 41 The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.

42 The Map Interface UML Diagram 42

43 Concrete Map Classes 43

44 HashMap and TreeMap 44 The HashMap and TreeMap classes are two concrete implementations of the Map interface. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order.

45 LinkedHashMap 45 LinkedHashMap was introduced in JDK 1.4. It extends HashMap with a linked list implementation that supports an ordering of the entries in the map. The entries in a HashMap are not ordered, but the entries in a LinkedHashMap can be retrieved in the order in which they were inserted into the map (known as the insertion order), or the order in which they were last accessed, from least recently accessed to most recently (access order). The no-arg constructor constructs a LinkedHashMap with the insertion order. To construct a LinkedHashMap with the access order, use the LinkedHashMap(initialCapacity, loadFactor, true).

46 Example: Using HashMap and TreeMap 46 This example creates a hash map that maps borrowers to mortgages. The program first creates a hash map with the borrower’s name as its key and mortgage as its value. The program then creates a tree map from the hash map, and displays the mappings in ascending order of the keys. RunTestMap

47 Example: Counting the Occurrences of Words in a Text 47 This program counts the occurrences of words in a text and displays the words and their occurrences in ascending order of the words. The program uses a hash map to store a pair consisting of a word and its count. For each word, check whether it is already a key in the map. If not, add the key and value 1 to the map. Otherwise, increase the value for the word (key) by 1 in the map. To sort the map, convert it to a tree map. RunCountOccurrenceOfWords

48 The Arrays Class 48 The Arrays class contains various static methods for sorting and searching arrays, for comparing arrays, and for filling array elements. It also contains a method for converting an array to a list.

49 The Arrays Class UML Diagram 49

50 Example: Using the Arrays Class 50 This example demonstrates using the methods in the Arrays class. The example creates an array of int values, fills part of the array with 50, sorts it, searches for an element, and compares the array with another array. RunTestArrays


Download ppt "Chapter 22 Java Collections Framework CIS265/506 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive."

Similar presentations


Ads by Google