Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Java Collection Framework

Similar presentations


Presentation on theme: "The Java Collection Framework"— Presentation transcript:

1 The Java Collection Framework
Chp 20. Lists, Stacks, Queues, and PriorityQueues Chp 21. Sets and Maps 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
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.
A collection is a container that stores objects.

4 Java Collection Framework hierarchy, cont.
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
The Collection interface is the root interface for manipulating a collection of objects.

6 The Set Interface 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

8 The AbstractSet Class 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 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: s0 * 31(n-1) + s1*31(n-2) + … + sn-1 where si is s.charAt(i).

10 Example: Using HashSet and Iterator
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<String> set = new HashSet<String>(); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); System.out.println( set ); // Obtain an iterator for the hash set Iterator<String> 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 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( , 22, 33, 44, 55, 66)); for (Object n : list){ System.out.println ( n ); }

12 Example: Using LinkedHashSet
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<String> set = new LinkedHashSet<String>(); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); 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
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 Implement the Comparable interface and provide your version of the compareTo method, or Implement the Comparator interface and supply your version of the compare and equals method.

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

15 Example: Using TreeSet to Sort Elements in a Set
public class TestTreeSet { public static void main(String[] args) { // Create a hash set Set<String> set = new HashSet<String>(); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); System.out.println("Unsorted set: \t" + set); TreeSet<String> treeSet = new TreeSet<String>(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
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
Sometimes you want to insert elements of different types into a TreeSet (say Circles, Triangles, Rectangles,…) The elements may not be instances of Comparable or are not comparable. You can define a comparator to compare these elements. To do so, create a class that implements the java.util.Comparator interface. The Comparator interface has two methods, compare and equals.

18 The Comparator Interface
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 Example: The Using Comparator to Sort Elements in a Set
The example creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. import java.util.Comparator; public class GeometricObjectComparator implements Comparator<GeometricObject> { 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; } Alternatively you may change the class GeometricObject and ask it to implement the interface Comparable<GeometricObject> TODO: Draw a hierarchy tree

20 Example: The Using Comparator to Sort Elements in a Set
The example creates a sorted tree set of geometric objects. public class TestTreeSetWithComparator { public static void main(String[] args) { // Create a tree set for geometric objects using a comparator Set<GeometricObject> set = new TreeSet<GeometricObject> ( 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); }

21 Example: The Using Comparator to Sort Elements in a Set
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 >>> Height: 5.0 Width: 4.0 Perimeter: 18.0 Area: 20.0 area = >>> Circle white >>> Radius: 40.0 Perimeter: Area:

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

23 The List Interface, cont.

24 The List Iterator

25 Array, ArrayList and LinkedList
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. A list can grow or shrink dynamically. In contrast an array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array.

26 ArrayList ArrayList implements List using an array.

27 LinkedList LinkedList implements List using an dynamic linked list

28 Example: Using ArrayList and LinkedList
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<String> list = new ArrayList<String>(); // 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
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
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 Legacy Style – Linked List
First Last Control previous data next - aa bb cc Data Nodes

32 Legacy Style – Linked List
previous data next aa package csu.matos; public class Node<E> { Node previous; E data; Node next; public Node(E data) { this.previous = null; this.data = data; this.next = null; } public String showNode() { return Integer.toHexString(this.hashCode()) + " [" + this.previous + ", " + this.data + ", " + this.next + "]"; Data Nodes

33 Legacy Style – Linked List
package csu.matos; public class LegacyList<E> { Node<E> first; Node<E> last; int size; public LegacyList() { this.first = null; this.last = null; size = 0; } public Node<E> insertTail (E data ){ Node<E> newNode = new Node<E>(data); size++; if ( last == null ){ last = newNode; first = newNode; return newNode; newNode.previous = last; last.next = newNode; last = newNode; public void showList(){ System.out.println("\nCONTROL: First=" + this.first + " Last=" + this.last); Node<E> ptr = first; while( ptr != null ){ System.out.println( ptr + ptr.showNode() ); ptr = ptr.next; First Last Control

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

35 Example: Using the Collections Interface
The example creates a list, sorts it, and searches for an element. public class TestCollectionMethods { public static void main(String[] args){ List<String> 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<String> 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<Integer> 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] 6 z 7 x 8 1 9 false 10 [nada, nada, nada] 11 2

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

37 The Stack Class 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. top push pop peek

38 Example: Using the Stack Class
public class TestingTheStackClass { public static void main(String[] args) { Stack<String> stack1 = new Stack<String>(); 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 ); } Console 0 [aaa, bbb, ccc, ddd] 1 4 2 ddd 3 true 4 aaa 5 true 6 0 7 xxx 8 [aaa, bbb, ccc, ddd] 7 ddd 8 [aaa, bbb, ccc] 7 ccc 8 [aaa, bbb] 7 bbb 8 [aaa] 7 aaa 8 []

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

40 The Queue Interface

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

42 The PriorityQueue Class
public class TestingPriorityQueue { public static void main(String[] arg) { PriorityQueue<String> queue1 = new PriorityQueue<String>(); 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<String>:\n Head>> "); while (queue1.size() > 0) { System.out.print(queue1.remove() + " "); } PriorityQueue<String> queue2 = new PriorityQueue<String>( 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"); while (queue2.size() > 0) { System.out.print(queue2.remove() + " "); CONSOLE Priority queue using default Comparable<String>: Head>> 01-data1 01-data3 01-data4 01-data6 02-data2 02-data5 Priority queue using default Comparator<String>: Head>> 02-data5 02-data2 01-data6 01-data4 01-data3 01-data1

43 The PriorityQueue Class
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 [ 01-data1, 01-data4, 01-data3, 02-data2, 02-data5, 01-data6 ] Console (using iterator ) Priority queue using Comparable: Head>> 01-data data data data data data5 Priority queue using Comparator: Head>> 02-data5 02-data2 01-data6 01-data4 01-data3 01-data1 43

44 Using Custom Comparator in PriorityQueue
public class Driver { public static void main(String[] args) { Comparator myComparator = new MyQueueComparator(); PriorityQueue<String> queue3 = new PriorityQueue<String>( 10, myComparator); queue3.offer("HIGH-data1"); queue3.offer("LOW-data2"); queue3.offer("LOW-data3"); queue3.offer("MEDIUM-data4"); queue3.offer("LOW-data5"); queue3.offer("HIGH-data6"); queue3.add ("MEDIUM-data7"); System.out.println("Priority queue using CUSTOM Comparator:\n Head>> "); while (queue3.size() > 0) { System.out.print(queue3.remove() + " "); } Console Priority queue using CUSTOM Comparator: Head>> HIGH-data1 HIGH-data6 MEDIUM-data4 MEDIUM-data7 LOW-data2 LOW-data3 LOW-data5 44

45 Using Custom Comparator in PriorityQueue
public class MyQueueComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { // change HIGH-data1 into 01-data1, LOW-datax into 03-datax String p1 = getPriority(s1) + s1.substring(s1.indexOf('-')); String p2 = getPriority(s2) + s2.substring(s2.indexOf('-')); if (p1.compareTo(p2) == 0) return 0; else if (p1.compareTo(p2) > 0) return +1; else return -1; } public static String getPriority(String element) { if (element.startsWith("HIGH")) return "01"; else if (element.startsWith("MEDIUM")) return "02"; return "03"; }// comparator 45

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

47 The Map Interface

48 Map Concrete Classes

49 HashMap, TreeMap, LinkedHashMap
The HashMap class is efficient for random key order operations such as: locating, inserting, and deleting an entry using a key. The entries in a HashMap are not ordered. The TreeMap class, implementing SortedMap, is efficient for traversing the map entries in in a sorted key order. To construct a LinkedHashMap with the insertion order, use: LinkedHashMap(initialCapacity, loadFactor, false). To construct a LinkedHashMap with the access order, use: LinkedHashMap(initialCapacity, loadFactor, true) (entries most recently accessed will appear at one extreme of the list). Maps are NOT iterable ( do not use Iterator or for-each loop, instead pass it to an iterable container such as array or set, or use firstKey(), higherKey(), lastKey(), lowerKey() … navigation ops )

50 Example: Using HashMap and TreeMap
public class TestHashMap { public static void main(String[] arg) { // Create a HashMap <String, Integer> = <personName, birthdateYear> Map<String, Integer> hashMap = new HashMap<String, Integer>(); hashMap.put("Moe", ); hashMap.put("Larry", 1902); hashMap.put("Curly", 1903); hashMap.put("Shemp", 1895); System.out.println("HashMap - arbitrary order"); System.out.println(hashMap); // Create a TreeMap from the previous HashMap Map<String, Integer> treeMap = new TreeMap<String, Integer>(hashMap); System.out.println("\nTreeMap - asc order of key (personName)"); System.out.println(treeMap); CONSOLE HashMap - arbitrary order {Moe=1897, Shemp=1895, Curly=1903, Larry=1902} TreeMap - asc order of key (personName) {Curly=1903, Larry=1902, Moe=1897, Shemp=1895}

51 Example: Using HashMap and TreeMap
// Create a LinkedHashMap Map<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>( 16, 0.75f, false ); linkedHashMap.put("Moe", ); linkedHashMap.put("Larry", 1902); linkedHashMap.put("Curly", 1903); linkedHashMap.put("Shemp", 1895); // retrieve Moe's data System.out.println("\nRetrieving Moe's data: " + linkedHashMap.get("Moe").intValue()); // retrieve Larry’s data System.out.println("\nRetrieving Larry's data: " + linkedHashMap.get("Larry").intValue()); System.out.println("\nLinkedHashMap - entries on insertion (false) / access (true) order"); System.out.println( linkedHashMap ); } Note: change it to “true”. Map will show Moe, then Larry as most recently accessed entries. CONSOLE Retrieving Moe's data: 1897 Retrieving Larry's data: 1902 LinkedHashMap - entries on insertion(false)/access(true) order {Moe=1897, Larry=1902, Curly=1903, Shemp=1895}

52 Example: Counting the Occurrences of Words in a Text
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.   Example: "And in the end, it is not the years in your life that count. It is the life in your years " Abraham Lincoln CONSOLE 1 count 1 end 3 in 2 is 2 it 2 life 1 not 1 that 3 the 2 years 2 your

53 Example: Counting the Occurrences of Words in a Text
public class CountWords { public static void main(String[] args) { // Set text in a string (Abraham Lincoln) String text = "And in the end, it is not the years in your life " + "that count. It is the life in your years"; // Create a TreeMap to hold words as key and count as value TreeMap<String, Integer> map = new TreeMap<String, Integer>(); String[] words = text.split("[ \n\t\r.,;:!?(){}]"); for (int i = 0; i < words.length; i++) { String key = words[i].toLowerCase(); if (words[i].length() > 1) { if (map.get(key) == null) { map.put(key, 1); } else { int value = map.get(key).intValue(); value++; map.put(key, value); System.out.println( map ); String key = map.firstKey(); Integer value = 0; while (key != null ){ value = map.get(key); System.out.println ( value + "\t" + key ); key = map.higherKey(key); CONSOLE { and=1, count=1, end=1, in=3, is=2, it=2, life=2, not=1, that=1, the=3, years=2, your=2 } CONSOLE 1 and 1 count 1 end 3 in 2 is 2 it 2 life 1 not 1 that 3 the 2 years 2 your

54 The Arrays Class 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.

55 The Arrays Class cont.

56 The Arrays Class cont.

57 Example: Using 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. public class TestArray { final static int N = 20; public static void main(String[] args) { int[] array1 = new int[N]; for (int i = 0; i < N; i++) { array1[i] = (int) (Math.random() * 101); } showArray("array1", array1); int[] array2 = Arrays.copyOf(array1, 10); int[] array3 = Arrays.copyOfRange(array1, 10, 20); showArray("array2", array2); showArray("array3", array3); Arrays.sort(array1); showArray("sorted array1", array1); int key = array1[((int) ((N + 1) * Math.random()))]; int position = Arrays.binarySearch(array1, key); System.out.printf("key %d at position %d\n", key, position); List<Integer> list1 = Arrays.asList(10, 20, 30, 40, 50, 60, 70); System.out.println(list1);

58 Example: Using 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. if (Arrays.equals(array1, array2)) System.out.println("array1 and array2 are the same"); else System.out.println("array1 and array2 are NOT the same"); }// main public static void showArray(String name, int[] array) { System.out.println(name); for (int i = 0; i < array.length; i++) { System.out.print(i + ":" + array[i] + " "); } System.out.println(); array1 0:87 1:25 2:11 3:8 4:18 5:80 6:39 7:97 8:83 9:72 10:45 11:39 12:46 13:32 14:24 15:96 16:89 17:22 18:86 19:94 array2 0:87 1:25 2:11 3:8 4:18 5:80 6:39 7:97 8:83 9:72 array3 0:45 1:39 2:46 3:32 4:24 5:96 6:89 7:22 8:86 9:94 sorted array1 0:8 1:11 2:18 3:22 4:24 5:25 6:32 7:39 8:39 9:45 10:46 11:72 12:80 13:83 14:86 15:87 16:89 17:94 18:96 19:97 key 86 at position 14 [10, 20, 30, 40, 50, 60, 70] array1 and array2 are NOT the same


Download ppt "The Java Collection Framework"

Similar presentations


Ads by Google