* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Chapter 22
Survey
Document related concepts
Reserved word wikipedia , lookup
Falcon (programming language) wikipedia , lookup
Name mangling wikipedia , lookup
Class (computer programming) wikipedia , lookup
Go (programming language) wikipedia , lookup
Scala (programming language) wikipedia , lookup
Selection algorithm wikipedia , lookup
C Sharp syntax wikipedia , lookup
Object-oriented programming wikipedia , lookup
Java (programming language) wikipedia , lookup
Design Patterns wikipedia , lookup
Transcript
1 Chapter 22 Java Collections Framework Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 2 Java Collections Framework • High-performance, high-quality implementation of common data structures. • Enables software-reuse. • Originally used type Object; Java SE 5 uses generics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 3 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. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Java Collection Framework hierarchy, cont. 4 Set and List are subinterfaces of Collection. SortedSet TreeSet Set AbstractSet Collection HashSet LinkedHashSet Vector Stack AbstractCollection AbstractList List ArrayList AbstractSequentialList LinkedList Deque Queue Interfaces AbstractQueue PriorityQueue Liang, Introduction to Java Programming, Seventh Edition, Classes (c) 2009 Pearson Education, Inc.Concrete All Classes Abstract rights reserved. 0136012671 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. SortedMap Map TreeMap AbstractMap Interfaces Abstract Classes HashMap Concrete Classes Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 LinkedHashMap 5 6 The Collection Interface «interface» java.util.Collection<E> The Collection interface is the root interface for manipulating a collection of objects. +add(o: E): boolean Adds a new element o to this collection. +addAll(c: Collection<? extends E): boolean Adds all the elements in the collection c to this collection. +clear(): void Removes all the elements from this collection. +contains(o: Object): boolean Returns true if this collection contains the element o. +containsAll(c: Collection<?>):boolean Returns true if this collection contains all the elements in c. +equals(o: Object): boolean Returns true if this collection is equal to another collection o. +hashCode(): int Returns the hash code for this collection. +isEmpty(): boolean Returns true if this collection contains no elements. +iterator(): Iterator Returns an iterator for the elements in this collection. +remove(o: Object): boolean Removes the element o from this collection. +removeAll(c: Collection<?>): boolean Removes all the elements in c from this collection. +retainAll(c: Collection<?>): boolean Retains the elements that are both in c and in this collection. +size(): int Returns the number of elements in this collection. +toArray(): Object[] Returns an array of Object for the elements in this collection. «interface» java.util.Iterator<E> +hasNext(): boolean Returns true if this iterator has more elements to traverse. +next(): E Returns the next element from this iterator. +remove(): void Removes the last element obtained using the next method. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 7 The Set Interface Set interface extends the Collection interface. No new methods or constants Stipulates that a Set contains no duplicate elements. The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. (i.e., e1 and e2 cannot be in the set when e1.equals(e2) is true.) Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 8 The Set Interface Hierarchy «interface» java.util.Collection<E> «interface» java.util.Set<E> «interface» java.util.AbstractSet<E> java.util.SortedSet<E> java.util.HashSet<E> +HashSet() +HashSet(c: Collection<? extends E>) java.util.LinkedHashSet<E> +LinkedHashSet() +LinkedHashSet(c: Collection<? extends E>) +first(): E Returns the first in this set. +last(): E Returns the last in this set. +headSet(toElement: E): SortedSet<E> headSet/tailSet returns a portion of the set less than toElement/greater than or equal to fromElement. +tailSet(fromElement: E): SortedSet<E> java.util.TreeSet<E> +TreeSet() +TreeSet(c: Collection<? extends E>) +TreeSet(c: Comparator<? super E>) Creates a tree set with the specified comparator. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 9 The AbstractSet Class AbstractSet class is a convenience class that extends AbstractCollection and implements Set. Provides concrete implementations for equals and hashCode. The hash code of a set is the sum of the hash code of all the elements in the set. Abstract class since the size and iterator methods are not implemented. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 10 The HashSet Class HashSet class is a concrete class that implements Set. It can be used to store elements that have no duplicates For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 11 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. TestHashSet Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 JDK 1.5 Feature 12 TIP: for-each loop You can simplify the code in Lines 21-26 using a JDK 1.5 enhanced for loop without using an iterator, as follows: for (Object element: set) System.out.print(element.toString() + " "); Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 13 Example: Using LinkedHashSet This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list. TestLinkedHashSet Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The SortedSet Interface and the TreeSet Class 14 SortedSet is a subinterface of Set Garantees that the elements 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 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The SortedSet Interface and the TreeSet Class, cont. 15 The elements of TreeSet can be sorted 1. Using the Comparable interface. 1. Specify a comparator for the elements in the set order by comparator. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Example: Using TreeSet to Sort Elements in a Set This example creates a hash set filled with strings, and then creates a tree set for the same strings. The strings are sorted in the tree set using the compareTo method in the Comparable interface. The example also creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. TestTreeSet Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 16 17 The Comparator Interface To insert elements of different types into a tree set. The elements may not be instances of Comparable or are not comparable. Define a comparator to compare these elements: Create a class that implements the java.util.Comparator interface. The Comparator interface has two methods, compare and equals to implement. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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. GeometricObjectComparator Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Example: The Using Comparator to Sort Elements in a Set Write a program that demonstrates how to sort elements in a tree set using the Comparator interface. The example creates a tree set of geometric objects. The geometric objects are sorted using the compare method in the Comparator interface. TestTreeSetWithComparator Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 19 20 The List Interface A set stores unique elements. To allow duplicate elements to be stored in a collection, use a list. User can specify where the element is stored and access by index. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The List Interface, cont. «interface» java.util.Collection<E> «interface» java.util.List<E> +add(index: int, element:E): boolean Adds a new element at the specified index. +addAll(index: int, c: Collection<? extends E>) : boolean Adds all the elements in c to this list at the specified index. +get(index: int): E Returns the element in this list at the specified index. +indexOf(element: Object): int Returns the index of the first matching element. +lastIndexOf(element: Object): int Returns the index of the last matching element. +listIterator(): ListIterator<E> Returns the list iterator for the elements in this list. +listIterator(startIndex: int): ListIterator<E> Returns the iterator for the elements from startIndex. +remove(index: int): E Removes the element at the specified index. +set(index: int, element: E): E Sets the element at the specified index. +subList(fromIndex: int, toIndex: int): List<E> Returns a sublist from fromIndex to toIndex. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 21 22 The List Iterator «interface» java.util.Iterator<E> «interface» java.util.ListIterator<E> +add(o: E): void Adds the specified object to the list. +hasPrevious(): boolean Returns true if this list iterator has more elements when traversing backward. +nextIndex(): int Returns the index of the next element. +previous(): E Returns the previous element in this list iterator. +previousIndex(): int Returns the index of the previous element. +set(o: E): void Replaces the last element returned by the previous or next method with the specified element. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 23 ArrayList and LinkedList ArrayList and LinkedList are concrete implementations of the List interface. ArrayList random access through an index, insert and remove elements from end. LinkedList allows insertion or deletion of elements anywhere in the list. A list can grow or shrink dynamically. Use an array if application does not require insertion or deletion of elements. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 24 java.util.ArrayList «interface» java.util.Collection<E> «interface» java.util.List<E> java.util.ArrayList<E> +ArrayList() Creates an empty list with the default initial capacity. +ArrayList(c: Collection<? extends E>) Creates an array list from an existing collection. +ArrayList(initialCapacity: int) Creates an empty list with the specified initial capacity. +trimToSize(): void Trims the capacity of this ArrayList instance to be the list's current size. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 java.util.LinkedList «interface» java.util.Collection<E> «interface» java.util.List<E> java.util.LinkedList<E> +LinkedList() Creates a default empty linked list. +LinkedList(c: Collection<? extends E>) Creates a linked list from an existing collection. +addFirst(o: E): void Adds the object to the head of this list. +addLast(o: E): void Adds the object to the tail of this list. +getFirst(): E Returns the first element from this list. +getLast(): E Returns the last element from this list. +removeFirst(): E Returns and removes the first element from this list. +removeLast(): E Returns and removes the last element from this list. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 25 Example: Using ArrayList and LinkedList This example creates an array list filled with numbers, and inserts new elements into the specified location in the list. The example also creates a linked list from the array list, inserts and removes the elements from the list. Finally, the example traverses the list forward and backward. TestList Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 26 The Collections Class 27 The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating readonly collection classes. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The Collections Class UML Diagram java.util.Collections List +sort(list: List): void Sorts the specified list. +sort(list: List, c: Comparator): void Sorts the specified list with the comparator. +binarySearch(list: List, key: Object): int Searches the key in the sorted list using binary search. +binarySearch(list: List, key: Object, c: Comparator): int Searches the key in the sorted list using binary search with the comparator. +reverse(list: List): void Reverses the specified list. +reverseOrder(): Comparator Returns a comparator with the reverse ordering. +shuffle(list: List): void Shuffles the specified list randomly. +shuffle(list: List): void Shuffles the specified list with a random object. +copy(des: List, src: List): void Copies from the source list to the destination list. +nCopies(n: int, o: Object): List Returns a list consisting of n copies of the object. +fill(list: List, o: Object): void Fills the list with the object. +max(c: Collection): Object Returns the max object in the collection. +max(c: Collection, c: Comparator): Object Returns the max object using the comparator. +min(c: Collection): Object Collection Returns the min object in the collection. +min(c: Collection, c: Comparator): Object Returns the min object using the comparator. +disjoint(c1: Collection, c2: Collection): boolean Returns true if c1 and c2 have no elements in common. +frequency(c: Collection, o: Object): int Returns the number of occurrences of the specified element in the collection. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 28 29 Example: Using the Collections Class This example demonstrates using the methods in the Collections class. The example creates a list, sorts it, and searches for an element. The example wraps the list into a synchronized and read-only list. TestCollections Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 30 The Vector and Stack Classes Java Collections Framework introduced with Java 2. Several data structures supported beforehand. Examples: Vector class and Stack class. Redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 31 The Vector Class In Java 2, Vector is the same as ArrayList, except that Vector contains the synchronized methods for accessing and modifying the vector. None of the new collection data structures introduced so far are synchronized. If synchronization is required, you can use the synchronized versions of the collection classes. These classes are introduced later in the section, “The Collections Class.” Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The Vector Class, cont. «interface» java.util.List<E> java.util.Vector<E> +Vector() Creates a default empty vector with initial capacity 10. +Vector(c: Collection<? extends E>) Creates a vector from an existing collection. +Vector(initialCapacity: int) Creates a vector with the specified initial capacity. +Vector(initCapacity:int, capacityIncr: int) Creates a vector with the specified initial capacity and increment. +addElement(o: E): void Appends the element to the end of this vector. +capacity(): int Returns the current capacity of this vector. +copyInto(anArray: Object[]): void Copies the elements in this vector to the array. +elementAt(index: int): E Returns the object at the specified index. +elements(): Enumeration<E> Returns an enumeration of this vector. +ensureCapacity(): void Increases the capacity of this vector. +firstElement(): E Returns the first element in this vector. +insertElementAt(o: E, index: int): void Inserts o to this vector at the specified index. +lastElement(): E Returns the last element in this vector. +removeAllElements(): void Removes all the elements in this vector. +removeElement(o: Object): boolean Removes the first matching element in this vector. +removeElementAt(index: int): void Removes the element at the specified index. +setElementAt(o: E, index: int): void Sets a new element at the specified index. +setSize(newSize: int): void Sets a new size in this vector. +trimToSize(): void Trims the capacity of this vector to its size. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 32 33 The Stack Class java.util.Vector<E> java.util.Stack<E> The Stack class represents a last-infirst-out stack of objects. The elements are accessed only from the top of the stack. You can retrieve, insert, or remove an element from the top of the stack. +Stack() Creates an empty stack. +empty(): boolean Returns true if this stack is empty. +peek(): E Returns the top element in this stack. +pop(): E Returns and removes the top element in this stack. +push(o: E) : E Adds a new element to the top of this stack. +search(o: Object) : int Returns the position of the specified element in this stack. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 34 Queues and Priority Queues A queue is a first-in/first-out 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. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 35 The Queue Interface «interface» java.util.Collection<E> «interface» java.util.Queue<E> +offer(element: E): boolean Inserts an element to the queue. +poll(): E Retrieves and removes the head of this queue, or null if this queue is empty. +remove(): E Retrieves and removes the head of this queue and throws an exception if this queue is empty. +peek(): E Retrieves, but does not remove, the head of this queue, returning null if this queue is empty. +element(): E Retrieves, but does not remove, the head of this queue, throwing an exception if this queue is empty. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 36 The PriorityQueue Class «interface» java.util.Queue<E> java.util.PriorityQueue<E> +PriorityQueue() Creates a default priority queue with initial capacity 11. +PriorityQueue(initialCapacity: int) Creates a default priority queue with the specified initial capacity. +PriorityQueue(c: Collection<? extends E>) Creates a priority queue with the specified collection. +PriorityQueue(initialCapacity: int, comparator: Comparator<? super E>) Creates a priority queue with the specified initial capacity and the comparator. PriorityQueueDemo Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The Map Interface The Map interface maps keys to the elements. keys are like indexes. List indexes are integer. Map keys can be any objects. Search keys Corresponding values Entry … . . Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 37 38 The Map Interface UML Diagram java.util.Map<K, V> +clear(): void Removes all mappings from this map. +containsKey(key: Object): boolean Returns true if this map contains a mapping for the specified key. +containsValue(value: Object): boolean Returns true if this map maps one or more keys to the specified value. +entrySet(): Set Returns a set consisting of the entries in this map. +get(key: Object): V Returns the value for the specified key in this map. +isEmpty(): boolean Returns true if this map contains no mappings. +keySet(): Set<K> Returns a set consisting of the keys in this map. +put(key: K, value: V): V Puts a mapping in this map. +putAll(m: Map): void Adds all the mappings from m to this map. +remove(key: Object): V Removes the mapping for the specified key. +size(): int Returns the number of mappings in this map. +values(): Collection<V> Returns a collection consisting of the values in this map. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 39 Concrete Map Classes «interface» java.util.Map<K, V> «interface» java.util.AbstractMap<K, V> java.util.SortedMap<K, V> +firstKey(): K java.util.HashMap<K, V> +HashMap() +HashMap(m: Map) +lastKey(): K +comparator(): Comparator<? super K>) +headMap(toKey: K): SortedMap +tailMap(fromKey: K): SortedMap java.util.LinkedHashMap<K, V> +LinkedHashMap() java.util.TreeMap<K, V> +LinkedHashMap(m: Map) +TreeMap() +LinkedHashMap(initialCapacity: int, loadFactor: float, accessOrder: boolean) +TreeMap(m: Map) +TreeMap(c: Comparator<? super K>) Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 HashMap and TreeMap 40 Concrete implementations of Map interface: HashMap and TreeMap. HashMap is efficient for locating a value, inserting a mapping, and deleting a mapping. TreeMap, implementing SortedMap, is efficient for traversing the keys in a sorted order. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 LinkedHashMap 41 LinkedHashMap extends HashMap with a linked list implementation that supports ordering the entries. HashMap entries are not ordered, but the entries in a LinkedHashMap can be retrieved in Insertion order - the order in which they were inserted Access order - the order in which they were last accessed, from least recently accessed to most recently Default: no-arg constructor constructs a LinkedHashMap with insertion order. To construct a LinkedHashMap with the access order, use LinkedHashMap(initialCapacity, loadFactor, true). Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Example: Using HashMap and TreeMap 42 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. TestMap Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Example: Counting the Occurrences of Words in a Text 43 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. CountOccurrenceOfWords Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Run 44 The Arrays Class The Arrays class contains various static methods sorting arrays searching arrays comparing arrays filling array elements convert array to list. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The Arrays Class UML Diagram Arrays +asList(a: Object[]): List Returns a list from an array of objects Overloaded binarySearch method for byte, char, short, int, long, float, double, and Object. Overloaded binary search method to search a key in the array of byte, char, short, int, long, float, double, and Object +binarySearch(a: xType[], key: xType): int Overloaded equals method for boolean, byte, char, short, int, long, float, double, and Object. +equals(a: xType[], a2: xType[]): boolean Overloaded fill method for boolean char, byte, short, int, long, float, double, and Object. +fill(a: xType[], val: xType): void Overloaded equals method that returns true if a is equal to a2 for a and a2 of the boolean, byte, char, short, int, long, float, and Object type Overloaded fill method to fill in the specified value into the array of the boolean, byte, char, short, int, long, float, and Object type +fill(a: xType[], fromIndex: int, toIndex: xType, val: xType): void Overloaded sort method for char, byte, short, int, long, float, double, and Object. +sort(a: xType[]): void Overloaded sort method to sort the specified array of the char, byte, short, int, long, float, double, and Object type +sort(a: xType[], fromIndex: int, toIndex: int): void Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 45 46 Example: Using the Arrays Class 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. TestArrays Run Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671