* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Chapter 19 Java Data Structures
Survey
Document related concepts
Falcon (programming language) wikipedia , lookup
Resource management (computing) wikipedia , lookup
Go (programming language) wikipedia , lookup
Name mangling wikipedia , lookup
Abstraction (computer science) wikipedia , lookup
Scala (programming language) wikipedia , lookup
Selection algorithm wikipedia , lookup
Object-relational impedance mismatch wikipedia , lookup
Class (computer programming) wikipedia , lookup
Java (programming language) wikipedia , lookup
Java performance wikipedia , lookup
C Sharp syntax wikipedia , lookup
Object lifetime wikipedia , lookup
C Sharp (programming language) wikipedia , lookup
Transcript
Collections Chapter 22 Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 1Patterns Place these programs on the desktop: TestSets (Team5) TestList (Team3) TestMap (Team4) TestCollections (Team2) •TestArrays (Team1) Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 2Patterns Objectives To describe the Java Collections Framework hierarchy •To use the Iterator interface to traverse through all the elements of a collection •To discover the Set interface, and know how and when to use HashSet, LinkedHashSet, or TreeSet to store elements •To compare elements using the Comparator interface •To explore the List interface, and know how and when to use ArrayList or LinkedList to store elements Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 3Patterns Introduction Java Collection Framework Hierarchy A collection is a container object (data structure) that represents a group of objects, often referred to as elements of the collection. The Java Collections Framework supports three major types of collections: –Set, list, map Y.Daniel to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & Patterns 4 Introduction contd. Java Collection Framework Hierarchy The set, list, and map collections are defined in the interfaces Set, List, and Map. Collections: The most common collection interface type Set: an unordered collection that does not allow duplicate elements Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 5Patterns Introduction contd. Java Collection Framework Hierarchy SortedSet: a set of whose elements are visited in sorted order List: stores ordered collection of elements Map stores a group of objects , each of which is associated with a key. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 6Patterns Introduction contd. Java Collection Framework Hierarchy HashSet: a set implementation that uses hashing to find the set elements TreeSet: a sorted set implementation that stores the elements in a balanced binary tree LinkedList and ArrayList: two implementation of the List interface Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 7Patterns <<Interface>> Collection LinkeditHashSet HashSet TreeSet <<Interface>> Set <<Interface>> SortedSet <<Interface>> List ArrayList LinkedList The relationships of the major interfaces and classes in the Java Collection Frameworks Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 8Patterns 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. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design & 9Patterns The AbstractCollection Class is a convenience class that provides partial implementation for the Collection interface. It implements all the methods in Collection except the size and iterator methods Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &10Patterns The Collection interface The Collection interface provides various query operations: •The size method returns the number of elements in the collection •The contains method checks whether the collection contains all the elements in the specified collection. •The isEmpty method returns true if the collection is empty Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &11Patterns Note : Some of the methods in the Collection interface cannot be implemented in the concrete subclass in this case, the method would throw java.lang.UnsupportedOperationException , a subclass of RuntimeException. This is a good design that you can use in your project. If a method has no meaning in the subclass, implement it public void someMethod() { throw new UnsupportedOperationException (“Method not supported”); Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &12Patterns 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 no two elements e1 and e2 can be in the set such that e1.equals(e2) is true. 13Design &13Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented The Set Interface Hierarchy «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 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. The three concrete classes of Set are HashSet, LinkedHashSet, and TreeSet. 14Design &14Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented The HashSet Class The HashSet class is a concrete class that implements Set. It can be used to store duplicatefree elements. For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code. i.e., the hashCode in the Integer class will return its int value The hashCode in the Character class will returns its Unicode value 15Design &15Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented The hashCode Method and the equals Method The hashCode() and the equals() method are defined in the Object class as well as in the Collection interface. With the same method signature. hashCode method and the equals method have default implementation in the Object class. A class that implements the Collection interface does not have to implement these methods. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &16Patterns The hashCode() Method The hash code of two objects must be the same if the two objects are equal. Two unequal objects may have the same hash code. but you must implement the hashCode method to avoid too many such cases. Additionally, it is required that invoking the hasCode method multiple times returns the same integer during one execution of the program Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &17Patterns Example TestSets This example creates: 1. A HashSet filled with strings, and uses an iterator to traverse the elements in the list. 2. 2. A LinkedHashSet – the elements are retrieved in the order they were entered into the set 3. A TreeSet – the elements are retrieved in a sorted order, they are sorted by using the compareTo method in the Comparable interface TestSet Run Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &18Patterns 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. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &19Patterns The List Interface, cont. Collection List +add(index: int, element: Object) : boolean Adds a new element at the specified index +addAll(index: int, collection: Collection) : Adds all elements in the collection to this list at the boolean specified index +get(index: int) : Object 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 Returns the list iterator for the elements in this list +listIterator(startIndex: int) : ListIterator Returns the iterator for the elements from startIndex +remove(index: int) : int Removes the element at the specified index +set(index: int, element: Object) : Object Sets the element at the specified index +subList(fromIndex: int, toIndex: int) : List Returns a sublist from fromIndex to toIndex 20Design &20Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented The List Iterator Iterator ListIterator +add(o: Object) : 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 +previousIndex() : int Returns the index of the previosu element +previous() : Object Returns the previous element in this list iterator +set(o: Object) : void Replaces the last element returned by the previous or next method with the specified element 21Design &21Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented ArrayList and LinkedList The ArrayList class and the LinkedList class are concrete implementations of the List interface. Which of the two classes you use depends on your specific needs. If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. 22Design &22Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented ArrayList and LinkedList 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. 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. 23Design &23Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented LinkedList List AbstractSequentialList LinkedList +addFirst(o: Object) : void Adds the object to the head of this list +addLast(o: Object) : void Adds the object to the tail of this list +getFirst() : Object Returns the first element from this list +getLast() : Object Returns the last element from this list +removeFirst() : Object Returns and removes the first element from this list +removeLast() : Object Returns and removes the last element from this list Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &24Patterns 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 Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &25Patterns The Vector and Stack Classes Several data structures were supported prior to Java 2. like: – the Vector class – the Stack class. These classes were redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &26Patterns The Vector Class In Java 2, Vector is the same as ArrayList Vector contains the synchronized methods for accessing and modifying the vector None of the new collection data structures introduced so far are synchronized. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &27Patterns Synchronized is a key word that denotes a block of code subjected to mutual exclusion of an algorithm - only one call to a synchronized method will be executed at a given time. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &28Patterns The Vector Class, cont. List Vector +addElement(o: Object): 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): Object Returns the object at the specified index +elements(): Enumeration Returns an emulation of this vector +ensureCapacity(): void Increases the capacity of this vector +firstElement(): Object Returns the first element in this vector +insertElementAt(o: Object, index: int): void Inserts o to this vector at the specified index +lastElement(): Object 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: Object, 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 29Design &29Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented The Stack Class Vector The Stack class represents a last-in-firstout (LIFO) 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 +empty(): boolean Returns true if this stack is empty +peek(): Object Returns the top element in this stack +pop(): Object Returns and removes the top element in this stack +push(o: Object) : Object Adds a new element to the top of this stack +search(o: Object) : int Returns the position of the specified element in this stack 30Design &30Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented The Queue Class Collection Queue +offer(element:Object) : boolean +pool() : Object +remove() : Object +peek() : Object +elemet(): Object) The queue class represents a first-in-first(FIFO) out queue of objects. The elements are appended at the end of the queue and removed at the Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &31Patterns beginning of the Queues A queue is similar to a stack except that you add items to one end of the queue (the tail) and remove them from the other end of the queue ( the head) of the queue. Queues store items in FIFO. Items are removed in the same order in which they were added. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &32Patterns The Priority Queue Class Queue PriorityQueue +PriorityQueue() +PriorityQueue(initialCapacity :int) +PriorityQueue(c:Collection) +PriorityQueue(initCapacity:int, comparable:Comparator) The priority queue class order its elements according to their natural ordering using Comparable Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &33Patterns The Map Interface Map interface maps +clear() : void +containsKey(key: Object) : boolean keys to the +containsValue(value: Object) : boolean +entrySet() : Set elements. +get(key: Object) : Object +isEmpty() : boolean The keys are +keySet() : Set like indexes. +put(key: Object, value: Object) : Object +putAll(m: Map) : void In List, the +remove(key: Object) : Object +size() : int indexes are +values() : Collection integer. In Map, the keys can be any Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &34 Patterns Map The Java Collection Framework hierarchy, cont. An instance of Map represents a group of objects, each of which is associated with a key. AbstractMap TreeMap HashMap Map SortedMap Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &35Patterns HashMap and TreeMap 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 Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &36Patterns order. LinkedHashMap The LinkedHashMap extends HashMap with linked list implementation. The entries in HashMap are not ordered The entries in LinkedHashMap can be retrieved – in insertion order , or Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &37Patterns – In access order Example Using HashMap and TreeMap and Linked Mapcreate the The program first HashMap with the students name as a key, and their age as the value The Program create a TreeMap from the HashMap to display the entries in ascending order of the keys Create a LinkedHashMap, add the same entries and displays the entries TestMap Run Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &38Patterns 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. 39Design &39Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented 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 Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &40Patterns 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. 41Design &41Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented 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 42Design &42Patterns Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented 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 TestArrays Run another array. Y.Daniel Liang Introduction to Java Programming Sixth Edition and Cay Horstmann Object-Oriented Design &43Patterns