Advanced Programming Language - Chapter III: Basic Data Structures

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

pdf119 trang | Chia sẻ: dntpro1256 | Lượt xem: 749 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Advanced Programming Language - Chapter III: Basic Data Structures, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
the last matching element in this list. Removes all the elements from this list. Returns the number of elements in this list. Removes the element at the specified index. Sets the element at the specified index. MyAbstractList #size: int #MyAbstractList() #MyAbstractList(objects: Object[]) +add(o: Object) : void +add(o: Object) : void +isEmpty(): boolean The size of the list. Creates a default list. Creates a list from an array of objects. Implements the add method. Implements the isEmpty method. Implements the size method. MyList MyAbstractList Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 44 Array Lists Array is a fixed-size data structure. Once an array is created, its size cannot be changed. Nevertheless, you can still use array to implement dynamic data structures. The trick is to create a new larger array to replace the current array if the current array cannot hold new elements in the list. Initially, an array, say data of Object[] type, is created with a default size. When inserting a new element into the array, first ensure there is enough room in the array. If not, create a new array with the size as twice as the current one. Copy the elements from the current array to the new array. The new array now becomes the current array. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 45 Insertion Before inserting a new element at a specified index, shift all the elements after the index to the right and increase the list size by 1. e0 0 1 i i+1 k-1 Before inserting e at insertion point i e1 ei ei+1 ek-1 data.length -1 Insertion point e e0 0 1 i i+1 After inserting e at insertion point i, list size is incremented by 1 e1 e ei ek-1 data.length -1 e inserted here ek ek k ei-1 ei-1 k+1 k ei+1 i+2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 46 Deletion To remove an element at a specified index, shift all the elements after the index to the left by one position and decrease the list size by 1. e0 0 1 i i+1 k-1 Before deleting the element at index i e1 ei ei+1 ek-1 data.length -1 Delete this element e0 0 1 i After deleting the element, list size is decremented by 1 e1 ek data.length -1 ek k ei-1 ei-1 k-1 ei+1 k-2 ek-1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 47 Implementing MyArrayList MyArrayList -data: Object[] +MyArrayList() +MyArrayList(objects: Object[]) MyAbstractList Creates a default array list. Creates an array list from an array of objects. MyArrayList Run TestList Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 48 Linked Lists Since MyArrayList is implemented using an array, the methods get(int index) and set(int index, Object o) for accessing and modifying an element through an index and the add(Object o) for adding an element at the end of the list are efficient. However, the methods add(int index, Object o) and remove(int index) are inefficient because it requires shifting potentially a large number of elements. You can use a linked structure to implement a list to improve efficiency for adding and remove an element anywhere in a list. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 49 Nodes in Linked Lists A linked list consists of nodes, as shown in Figure 20.7. Each node contains an element, and each node is linked to its next neighbor. Thus a node can be defined as a class, as follows: first element next element next element next last node1 node2 node n class Node { Object element; Node next; public Node(Object o) { element = o; } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 50 Nodes in a Linked List The variable first refers to the first node in the list, and the variable last refers to the last node in the list. If the list is empty, both are null. For example, you can create three nodes to store three circle objects (radius 1, 2, and 3) in a list: Node first, last; // Create a node to store the first circle object first = new Node(new Circle(1)); last = first; // Create a node to store the second circle object last.next = new Node(new Circle(2)); last = last.next; // Create a node to store the third circle object last.next = new Node(new Circle(3)); last = last.next; Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 51 MyLinkedList MyLinkedList -first: Node -last: Node +LinkedList() +LinkedList(objects: Object[]) +addFirst(o: Object): void +addLast(o: Object): void +getFirst(): Object +getLast(): Object +removeFirst(): Object +removeLast(): Object 1 m Node element: Object next: Node Link 1 MyAbstractList Creates a default linked list. Creates a linked list from an array of objects. Adds the object to the head of the list. Adds the object to the tail of the list. Returns the first object in the list. Returns the last object in the list. Removes the first object from the list. Removes the last object from the list. My LinkedList Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 52 The addFirst(Object o) Method Since variable size is defined as protected in MyAbstractList, it can be accessed in MyLinkedList. When a new element is added to the list, size is incremented by 1, and when an element is removed from the list, size is decremented by 1. The addFirst(Object o) method (Line 20-28) creates a new node to store the element and insert the node to the beginning of the list. After the insertion, first should refer to this new element node. first e0 next A new node to be inserted here ei next ei+1 next last ek next o next New node inserted here (A) Before a new node is inserted. (B) After a new node is inserted. e0 next ei next ei+1 next last ek next o next first Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 53 The addLast(Object o) Method The addLast(Object o) method (Lines 31-41) creates a node to hold element o and insert the node to the end of the list. After the insertion, last should refer to this new element node. first e0 next ei next ei+1 next last ek next o next New node inserted here (A) Before a new node is inserted. (B) After a new node is inserted. first e0 next ei next ei+1 next last ek next A new node to be inserted here o next Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 54 The add(int index, Object o) Method The add(int index, Object o) method (Lines 45-57) adds an element o to the list at the specified index. Consider three cases: (1) if index is 0, invoke addFirst(o) to insert the element to the beginning of the list; (2) if index is greater than or equal to size, invoke addLast(o) to insert the element to the end of the list; (3) create a new node to store the new element and locate where to insert the new element. As shown in Figure 20.12, the new node is to be inserted between the nodes current and temp. The method assigns the new node to current.next and assigns temp to the new node’s next. current first e0 next A new node to be inserted here ei next temp ei+1 next last ek next o next current first ei next New node inserted here ei next temp ei+1 next last ek next o next (A) Before a new node is inserted. (B) After a new node is inserted. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 55 The removeFirst() Method The removeFirst() method (Lines 61-69) removes the first node in the list by pointing first to the second node, as shown in Figure 20.13. The removeLast() method (Lines 73-88) removes the last node from the list. Afterwards, last should refer to the former second-last node. first e0 next Delete this node ei next ei+1 next last ek next (a) Before the node is deleted. (b) After the first node is deleted e1 next ei next ei+1 next last ek next e1 next first Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 56 Stacks and Queues A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack. A queue represents a waiting list. A queue can be viewed as a special type of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue. Since the insertion and deletion operations on a stack are made only the end of the stack, using an array list to implement a stack is more efficient than a linked list. Since deletions are made at the beginning of the list, it is more efficient to implement a queue using a linked list than an array list. This section implements a stack class using an array list and a queue using a linked list. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 57 Design of the Stack and Queue Classes There are two ways to design the stack and queue classes: · Using inheritance: You can declare the stack class by extending the array list class, and the queue class by extending the linked list class. · Using composition: You can declare an array list as a data field in the stack class, and a linked list as a data field in the queue class. Both designs are fine, but using composition is better because it enables you to declare a complete new stack class and queue class without inheriting the unnecessary and inappropriate methods from the array list and linked list. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 58 MyStack and MyQueue MyStack -list: MyArrayList +isEmpty(): boolean +getSize(): int +peek(): Object +pop(): Object +push(o: Object): Object +search(o: Object): int Returns true if this stack is empty. Returns the number of elements in this stack. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Returns the position of the specified element in this stack. MyQueue -list: MyLinkedList +enqueue(element: Object): void +dequeue(): Object +getSize(): int Adds an element to this queue. Removes an element from this queue. Returns the number of elements from this queue. MyStack MyQueue Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 59 Example: Using Stacks and Queues TestStackQueue Write a program that creates a stack using MyStack and a queue using MyQueue. It then uses the push (enqueue) method to add strings to the stack (queue) and the pop (dequeue) method to remove strings from the stack (queue). Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 60 Binary Trees A list, stack, or queue is a linear structure that consists of a sequence of elements. A binary tree is a hierarchical structure. It is either empty or consists of an element, called the root, and two distinct binary trees, called the left subtree and right subtree. Examples of binary trees are shown in Figure 20.18. 60 55 100 57 67 107 45 G F R M T A (A) (B) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 61 Binary Tree Terms The root of left (right) subtree of a node is called a left (right) child of the node. A node without children is called a leaf. A special type of binary tree called a binary search tree is often useful. A binary search tree (with no duplicate elements) has the property that for every node in the tree the value of any node in its left subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node. The binary trees in Figure 20.18 are all binary search trees. This section is concerned with binary search trees. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 62 Representing Binary Trees A binary tree can be represented using a set of linked nodes. Each node contains a value and two links named left and right that reference the left child and right child, respectively, as shown in Figure 20.19. 60 55 100 57 45 67 107 root class TreeNode { Object element; TreeNode left; TreeNode right; public TreeNode(Object o) { element = o; } Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 63 Inserting an Element to a Binary Tree If a binary tree is empty, create a root node with the new element. Otherwise, locate the parent node for the new element node. If the new element is less than the parent element, the node for the new element becomes the left child of the parent. If the new element is greater than the parent element, the node for the new element becomes the right child of the parent. Here is the algorithm: Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 64 Inserting an Element to a Binary Tree if (root == null) root = new TreeNode(element); else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); return true; // Element inserted } For example, to insert 101 into the tree in Figure 20.19, the parent is the node for 107. The new node for 101 becomes the left child of the parent. To insert 59 into the tree, the parent is the node for 57. The new node for 59 becomes the right child of the parent, as shown in Figure 20.20. 60 55 100 57 45 67 107 root 59 101 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 65 Tree Traversal Tree traversal is the process of visiting each node in the tree exactly once. There are several ways to traverse a tree. This section presents inorder, preorder, postorder, depth- first, and breadth-first traversals. The inorder traversal is to visit the left subtree of the current node first, then the current node itself, and finally the right subtree of the current node. The postorder traversal is to visit the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 66 Tree Traversal, cont. The breadth-first traversal is to visit the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. For example, in the tree in Figure 20.20, the inorder is 45 55 57 59 60 67 100 101 107. The postorder is 45 59 57 55 67 101 107 100 60. The preorder is 60 55 45 57 59 100 67 107 101. The breadth-first traversal is 60 55 100 45 57 67 107 59 101. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 67 The BinaryTree Class Let’s define the binary tree class, named BinaryTree with the insert, inorder traversal, postorder traversal, and preorder traversal, as shown in Figure 20.21. Its implementation is given as follows: BinaryTree -root: TreeNode +BinaryTree() +BinaryTree(objects: Object[]) +insert(o: Object): boolean +inorder(): void +preorder(): void +postorder(): void 1 m TreeNode element: Object left: TreeNode right: TreeNode Link 1 Creates a default binary tree. Creates a binary tree from an array of objects. Adds an element to the binary tree. Prints the nodes in inorder traversal. Prints the nodes in preorder traversal. Prints the nodes in postorder traversal. BinaryTree Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 68 Example: Using Binary Trees Write a program that creates a binary tree using BinaryTree. Add strings into the binary tree and traverse the tree in inorder, postorder, and preorder. BinaryTree Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 69 Heap Heap is a useful data structure for designing efficient sorting algorithms and priority queues. A heap is a binary tree with the following properties: It is a complete binary tree. Each node is greater than or equal to any of its children. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 70 Complete Binary Tree A binary tree is complete if every level of the tree is full except that the last level may not be full and all the leaves on the last level are placed left-most. For example, in Figure 20.23, the binary trees in (a) and (b) are complete, but the binary trees in (c) and (d) are not complete. Further, the binary tree in (a) is a heap, but the binary tree in (b) is not a heap, because the root (39) is less than its right child (42). 22 29 14 33 32 39 42 22 29 14 32 42 39 22 14 33 32 39 42 22 29 32 42 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 71 Representing a Heap For a node at position i, its left child is at position 2i+1 and its right child is at position 2i+2, and its parent is (i-1)/2. For example, the node for element 39 is at position 4, so its left child (element 14) is at 9 (2*4+1), its right child (element 33) is at 10 (2*4+2), and its parent (element 42) is at 1 ((4-1)/2). 22 29 14 33 17 30 9 32 39 44 13 42 59 62 62 42 59 32 39 44 13 22 29 14 33 17 30 9 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11][12][13] [10][11] Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 72 Rebuilding a Heap 22 29 14 33 17 30 32 39 44 13 42 59 9 (a) After moving 9 to the root 22 29 14 33 17 30 32 39 44 13 42 9 59 (b) After swapping 9 with 59 22 29 14 33 17 30 32 39 9 13 42 44 59 (c) After swapping 9 with 44 22 29 14 33 17 9 32 39 30 13 42 44 59 (d) After swapping 9 with 30 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 73 Removing the Root 22 29 14 33 17 30 32 39 44 13 42 59 9 (a) After moving 9 to the root 22 29 14 33 17 30 32 39 44 13 42 9 59 (b) After swapping 9 with 59 22 29 14 33 17 30 32 39 9 13 42 44 59 (c) After swapping 9 with 44 22 29 14 33 17 9 32 39 30 13 42 44 59 (d) After swapping 9 with 30 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 74 Adding a New Node 22 29 14 33 17 88 32 39 30 13 42 44 59 (a) Add 88 into an existing heap 22 29 14 33 17 30 32 39 88 13 42 44 59 (b) After swapping 88 with 30 22 29 14 33 17 30 32 39 44 13 42 88 59 (c) After swapping 88 with 44 22 29 14 33 17 30 32 39 44 13 42 59 88 (d) After swapping 88 with 59 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 75 The Heap Class Heap -list: java.util.ArrayList +Heap() +Heap(objects: Object[]) +remove(): Object +add(newObject: Object): void +getSize(): int Creates a default heap. Creates a heap with the specified objects. Removes the root from the heap and returns it. Adds a new object to the heap. Returns the size of the heap. Heap Run TestHeap Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 76 Priority Queue A regular queue is a first-in and 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 with priorities. When accessing elements, the element with the highest priority is removed first. A priority queue has a largest-in, first-out behavior. For example, the emergency room in a hospital assigns patients with priority numbers; the patient with the highest priority is treated first. MyPriorityQueue -heap: Heap +enqueue(element: Object): void +dequeue(): Object +getSize(): int Adds an element to this queue. Removes an element from this queue. Returns the number of elements from this queue. MyPriorityQueue Run TestPriorityQueue Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 77 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, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 78 Java Collection Framework hierarchy, cont. Set and List are subinterfaces of Collection. Set SortedSet AbstractSet Collection TreeSet HashSet List AbstractList AbstractSequentialList ArrayList LinkedList AbstractCollection Vector Stack LinkedHashSet Interfaces Abstract Classes Concrete Classes Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 79 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 HashMap AbstractMap LinkedHashMap Interfaces Abstract Classes Concrete Classes Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 80 The Collection Interface «interface» java.util.Collection +add(o: E): boolean +addAll(c: Collection<? extends E): boolean +clear(): void +contains(o: Object): boolean +containsAll(c: Collection):boolean +equals(o: Object): boolean +hashCode(): int +isEmpty(): boolean +iterator(): Iterator +remove(o: Object): boolean +removeAll(c: Collection): boolean +retainAll(c: Collection): boolean +size(): int +toArray(): Object[] Adds a new element o to this collection. Adds all the elements in the collection c to this collection. Removes all the elements from this collection. Returns true if this collection contains the element o. Returns true if this collection contains all the elements in c. Returns true if this collection is equal to another collection o. Returns the hash code for this collection. Returns true if this collection contains no elements. Returns an iterator for the elements in this collection. Removes the element o from this collection. Removes all the elements in c from this collection. Retains the elements that are both in c and in this collection. Returns the number of elements in this collection. Returns an array of Object for the elements in this collection. «interface» java.util.Iterator +hasNext(): boolean +next(): E +remove(): void Returns true if this iterator has more elements to traverse. Returns the next element from this iterator. Removes the last element obtained using the next method. The Collection interface is the root interface for manipulating a collection of objects. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 81 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 82 The Set Interface Hierarchy java.util.AbstractSet java.util.HashSet +HashSet() +HashSet(c: Collection) java.util.LinkedHashSet +LinkedHashSet() +LinkedHashSet(c: Collection<? extends E>) java.util.TreeSet +TreeSet() +TreeSet(c: Collection) +TreeSet(c: Comparator) «interface» java.util.SortedSet +first(): E +last(): E +headSet(toElement: E): SortedSet +tailSet(fromElement: E): SortedSet «interface» java.util.Set Returns the first in this set. Returns the last in this set. headSet/tailSet returns a portion of the set less than toElement/greater than fromElement. Creates a tree set with the specified comparator. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 83 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 84 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 the hash code. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 85 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, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 86 TIP 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() + " "); JDK 1.5 Feature Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 87 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, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 88 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 89 The SortedSet Interface and the TreeSet Class, cont. One way is to use the Comparable interface. The other way is to specify a comparator for the elements in the set if the class for the elements does not implement the Comparable interface, or you don’t want to use the compareTo method in the class that implements the Comparable interface. This approach is referred to as order by comparator. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 90 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. GeometricObjectComparator Run TestTreeSet Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 91 The Comparator Interface Sometimes you want to insert elements of different types into a tree set. 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 92 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 93 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, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 94 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 95 The List Interface, cont. List +add(index: int, element: Object) : boolean +addAll(index: int, collection: Collection) : boolean +get(index: int) : Object +indexOf(element: Object) : int +lastIndexOf(element: Object) : int +listIterator() : ListIterator +listIterator(startIndex: int) : ListIterator +remove(index: int) : int +set(index: int, element: Object) : Object +subList(fromIndex: int, toIndex: int) : List Collection Adds a new element at the specified index Adds all elements in the collection to this list at the specified index Returns the element in this list at the specified index Returns the index of the first matching element Returns the index of the last matching element Returns the list iterator for the elements in this list Returns the iterator for the elements from startIndex Removes the element at the specified index Sets the element at the specified index Returns a sublist from fromIndex to toIndex Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 96 The List Iterator ListIterator +add(o: Object) : void +hasPrevious() : boolean +nextIndex() : int +previousIndex() : int +previous() : Object +set(o: Object) : void Iterator Adds the specified object to the list Returns true if this list iterator has more elements when traversing backward. Returns the index of the next element Returns the index of the previosu element Returns the previous element in this list iterator Replaces the last element returned by the previous or next method with the specified element Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 97 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. 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 98 LinkedList LinkedList +addFirst(o: Object) : void +addLast(o: Object) : void +getFirst() : Object +getLast() : Object +removeFirst() : Object +removeLast() : Object List AbstractSequentialList Adds the object to the head of this list Adds the object to the tail of this list Returns the first element from this list Returns the last element from this list Returns and removes the first element from this list Returns and removes the last element from this list Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 99 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. Run TestList Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 100 The Vector and Stack Classes The Java Collections Framework was introduced with Java 2. Several data structures were supported prior to Java 2. Among them are the Vector class and the Stack class. These classes were redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility. This section introduces the Vector class and the Stack class. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 101 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, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 102 The Vector Class, cont. Vector +addElement(o: Object): void +capacity(): int +copyInto(anArray: Object[]): void +elementAt(index: int): Object +elements(): Enumeration +ensureCapacity(): void +firstElement(): Object +insertElementAt(o: Object, index: int): void +lastElement(): Object +removeAllElements() : void +removeElement(o: Object) : boolean +removeElementAt(index: int) : void +setElementAt(o: Object, index: int) : void +setSize(newSize: int) : void +trimToSize() : void List Appends the element to the end of this vector Returns the current capacity of this vector Copies the elements in this vector to the array Returns the object at the specified index Returns an emulation of this vector Increases the capacity of this vector Returns the first element in this vector Inserts o to this vector at the specified index Returns the last element in this vector Removes all the elements in this vector Removes the first matching element in this vector Removes the element at the specified index Sets a new element at the specified index Sets a new size in this vector Trims the capacity of this vector to its size Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 103 The Stack Class The Stack class represents a last-in- first-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 +empty(): boolean +peek(): Object +pop(): Object +push(o: Object) : Object +search(o: Object) : int Vector Returns true if this stack is empty Returns the top element in this stack Returns and removes the top element in this stack Adds a new element to the top of this stack Returns the position of the specified element in this stack Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 104 Example: Using the Vector Class Listing 4.1, PrimeNumber.java, determines whether a number n is prime by checking whether 2, 3, 4, 5, 6, ..., n/2 is a divisor. If a divisor is found, n is not prime. A more efficient approach to determine whether n is prime is to check if any of the prime numbers less than or equal to can divide n evenly. If not, n is prime. Write a program that finds all the prime numbers less than 250. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 105 Example: Using the Vector Class, cont. The program stores the prime numbers in a vector. Initially, the vector is empty. For n = 2, 3, 4, 5, ..., 250, the program determines whether n is prime by checking if any prime number less than or equal to in the vector is a divisor for n. If not, n is prime and add n to the vector. The program that uses a vector is given below. Run FindPrimeUsingVector Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 106 Example: Using the Stack Class Write a program that reads a positive integer and displays all its distinct prime factors in decreasing order. For example, if the input integer is 6, its distinct prime factors displayed are 3, 2; if the input integer is 12, the distinct prime factors are also 3 and 2. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 107 Example: Using the Stack Class, cont. The program uses a stack to store all the distinct prime factors. Initially, the stack is empty. To find all the distinct prime factors for an integer n, use the following algorithm: Run FindPrimeFactorUsingStack Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 108 The Map Interface 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 109 The Map Interface UML Diagram Map +clear(): void +containsKey(key: Object): boolean +containsValue(value: Object): boolean +entrySet(): Set +get(key: Object): Object +isEmpty(): boolean +keySet(): Set +put(key: Object, value: Object): Object +putAll(m: Map): void +remove(key: Object): Object +size(): int +values(): Collection Removes all mappings from this map Returns true if this map contains a mapping for the specified key. Returns true if this map maps one or more keys to the specified value. Returns a set consisting of the entries in this map Returns the value for the specified key in this map Returns true if this map contains no mappings Returns a set consisting of the keys in this map Puts a mapping in this map Adds all mappings from m to this map Removes the mapping for the specified key Returns the number of mappings in this map Returns a collection consisting of values in this map Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 110 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 order. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 111 LinkedHashMap 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). Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 112 Example: Using HashMap and TreeMap 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. Run TestMap Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 113 Example: Counting the Occurrences of Words in a Text 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. Run CountOccurrenceOfWords Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 114 The Collections Class The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating read- only collection classes. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 115 The Collections Class UML Diagram java.util.Collections +sort(list: List): void +sort(list: List, c: Comparator): void +binarySearch(list: List, key: Object): int +binarySearch(list: List, key: Object, c: Comparator): int +reverse(list: List): void +reverseOrder(): Comparator +shuffle(list: List): void +shuffle(list: List): void +copy(des: List, src: List): void +nCopies(n: int, o: Object): List +fill(list: List, o: Object): void +max(c: Collection): Object +max(c: Collection, c: Comparator): Object +min(c: Collection): Object +min(c: Collection, c: Comparator): Object +disjoint(c1: Collection, c2: Collection): boolean +frequency(c: Collection, o: Object): int Sorts the specified list. Sorts the specified list with the comparator. Searches the key in the sorted list using binary search. Searches the key in the sorted list using binary search with the comparator. Reverses the specified list. Returns a comparator with the reverse ordering. Shuffles the specified list randomly. Shuffles the specified list with a random object. Copies from the source list to the destination list. Returns a list consisting of n copies of the object. Fills the list with the object. Returns the max object in the collection. Returns the max object using the comparator. Returns the min object in the collection. Returns the min object using the comparator. Returns true if c1 and c2 have no elements in common. Returns the number of occurrences of the specified element in the collection. List Collection Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 116 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. Run TestCollections Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 117 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 118 The Arrays Class UML Diagram Arrays +asList(a: Object[]): List Overloaded binarySearch method for 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 +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 +sort(a: xType[], fromIndex: int, toIndex: int): void Returns a list from an array of objects Overloaded binary search method to search a key in the array of byte, char, short, int, long, float, double, and Object 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 Overloaded sort method to sort the specified array of the char, byte, short, int, long, float, double, and Object type Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 119 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. Run TestArrays

Các file đính kèm theo tài liệu này:

  • pdfadvanced_programminglanguage_nguyencaodat_c3_4443_1811635.pdf
Tài liệu liên quan