Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 BASIC DATA STRUCTURES Chapter.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 BASIC DATA STRUCTURES Chapter."— Presentation transcript:

1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 BASIC DATA STRUCTURES Chapter III 1

2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 2 What is a Data Structure? A data structure is a collection of data organized in some fashion. A data structure not only stores data, but also supports the operations for manipulating data in the structure. For example, an array is a data structure that holds a collection of data in sequential order. You can find the size of the array, store, retrieve, and modify data in the array. Array is simple and easy to use, but it has two limitations:

3 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 3 Introducing Arrays Array is a data structure that represents a collection of the same types of data.

4 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 4 Declaring Array Variables F datatype[] arrayRefVar; Example: double[] myList;  datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];

5 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 5 Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.

6 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 6 Declaring and Creating in One Step F datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; F datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];

7 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 7 The Length of an Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length For example, myList.length returns 10

8 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 8 Default Values When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.

9 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 9 Array Initializers F Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.

10 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 10 Enhanced for Loop JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array. JDK 1.5 Feature

11 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 11 Example: Testing Arrays F Objective: The program receives 6 numbers from the user, finds the largest number and counts the occurrence of the largest number entered. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4. TestArray Run

12 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 12 Example: Assigning Grades F Objective: read student scores (int), get the best score, and then assign grades based on the following scheme: –Grade is A if score is >= best–10; –Grade is B if score is >= best–20; –Grade is C if score is >= best–30; –Grade is D if score is >= best–40; –Grade is F otherwise. AssignGrade Run

13 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 13 Copying Arrays Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1;

14 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 14 Copying Arrays Using a loop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];

15 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 15 The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

16 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 16 Passing Arrays to Methods public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } Invoke the method int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); Invoke the method printArray(new int[]{3, 1, 2, 6, 4, 2}); Anonymous array

17 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 17 Anonymous Array The statement printArray(new int[]{3, 1, 2, 6, 4, 2}); creates an array using the following syntax: new dataType[]{literal0, literal1,..., literalk}; There is no explicit reference variable for the array. Such array is called an anonymous array.

18 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 18 Pass By Value Java uses pass by value to pass parameters to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. F For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. F For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.

19 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 19 public class Test { public static void main(String[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y represents an array of int values m(x, y); // Invoke m with arguments x and y System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); } public static void m(int number, int[] numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0] } Simple Example

20 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 20 Returning an Array from a Method public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; } int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); list result

21 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 21 Example: Counting Occurrence of Each Letter F Generate 100 lowercase letters randomly and assign to an array of characters. F Count the occurrence of each letter in the array. CountLettersInArrayRun

22 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 22 Two-dimensional Arrays // Declare array ref var dataType[][] refVar; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType[][] refVar = new dataType[10][10]; // Alternative syntax dataType refVar[][] = new dataType[10][10];

23 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 23 Declaring Variables of Two- dimensional Arrays and Creating Two-dimensional Arrays int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); double[][] x;

24 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 24 Two-dimensional Array Illustration array.length? 4 array[0].length? 3 matrix.length? 5 matrix[0].length? 5

25 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 25 Declaring, Creating, and Initializing Using Shorthand Notations You can also use an array initializer to declare, create and initialize a two-dimensional array. For example, int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Same as

26 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 26 Lengths of Two-dimensional Arrays int[][] x = new int[3][4];

27 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 27 Lengths of Two-dimensional Arrays, cont. int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length array[3].length array[4].length ArrayIndexOutOfBoundsException

28 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 28 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1

29 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 29 Ragged Arrays, cont.

30 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 30 Example: Grading Multiple- Choice Test F Objective: write a program that grades multiple-choice test. GradeExamRun

31 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 31 Example: Computing Taxes Using Arrays Liting 5.4, “Computing Taxes with Methods,” simplified Listing 3.4, “Computing Taxes.” Listing 5.4 can be further improved using arrays. Rewrite Listing 3.1 using arrays to store tax rates and brackets. ComputeTaxRun

32 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 32 600012000600010000 27950467002335037450 677001128505642596745 14125017195085975156600 307050 153525307050 10% 15% 27% 30% 35% 38.6% Refine the table

33 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 33 60002795067700141250307050 1200046700112850171950307050 6000233505642585975153525 100003745096745156600307050 Rotate Single filer Married jointly Married separately Head of household 600012000600010000 27950467002335037450 677001128505642596745 14125017195085975156600 307050 153525307050 Reorganize the table

34 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 34 int[][] brackets = { {6000, 27950, 67700, 141250, 307050}, // Single filer {12000, 46700, 112850, 171950, 307050}, // Married jointly {6000, 23350, 56425, 85975, 153525}, // Married separately {10000, 37450, 96700, 156600, 307050} // Head of household }; 10% 15% 27% 30% 35% 38.6% double[] rates = {0.10, 0.15, 0.27, 0.30, 0.35, 0.386}; 60002795067700141250307050 1200046700112850171950307050 6000233505642585975153525 100003745096745156600307050 Single filer Married jointly Married separately Head of household Declare Two Arrays

35 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 35 Multidimensional Arrays Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n- dimensional arrays for n >= 3. For example, the following syntax declares a three-dimensional array variable scores, creates an array, and assigns its reference to scores. double[][][] scores = new double[10][5][2];

36 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 36 Example: Calculating Total Scores F Objective: write a program that calculates the total score for students in a class. Suppose the scores are stored in a three- dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i’s student on the j’s exam. Your program displays the total score for each student. TotalScoreRun

37 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 37 Limitations of arrays F Once an array is created, its size cannot be altered. F Array provides inadequate support for inserting, deleting, sorting, and searching operations.

38 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 38 Object-Oriented Data Structure In object-oriented thinking, a data structure is an object that stores other objects, referred to as data or elements. So some people refer a data structure as a container object or a collection object. To define a data structure is essentially to declare a class. The class for a data structure should use data fields to store data and provide methods to support operations such as insertion and deletion. To create a data structure is therefore to create an instance from the class. You can then apply the methods on the instance to manipulate the data structure such as inserting an element to the data structure or deleting an element from the data structure.

39 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 39 Four Classic Data Structures Four classic dynamic data structures to be introduced in this chapter are lists, stacks, queues, and binary trees. A list is a collection of data stored sequentially. It supports insertion and deletion anywhere in the list. A stack can be perceived as a special type of the list where insertions and deletions take place only at the one end, referred to as the top of a stack. A queue represents a waiting list, where insertions take place at the back (also referred to as the tail of) of a queue and deletions take place from the front (also referred to as the head of) of a queue. A binary tree is a data structure to support searching, sorting, inserting, and deleting data efficiently.

40 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 40 Lists A list is a popular data structure to store data in sequential order. For example, a list of students, a list of available rooms, a list of cities, and a list of books, etc. can be stored using lists. The common operations on a list are usually the following: · Retrieve an element from this list. · Insert a new element to this list. · Delete an element from this list. · Find how many elements are in this list. · Find if an element is in this list. · Find if this list is empty.

41 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 41 Two Ways to Implement Lists There are two ways to implement a list. One is to use an array to store the elements. The array is dynamically created. If the capacity of the array is exceeded, create a new larger array and copy all the elements from the current array to the new array. The other approach is to use a linked structure. A linked structure consists of nodes. Each node is dynamically created to hold an element. All the nodes are linked together to form a list.

42 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 42 Design of ArrayList and LinkedList For convenience, let’s name these two classes: MyArrayList and MyLinkedList. These two classes have common operations, but different data fields. The common operations can be generalized in an interface or an abstract class. A good strategy is to combine the virtues of interfaces and abstract classes by providing both interface and abstract class in the design so the user can use either the interface or the abstract class whichever is convenient. Such an abstract class is known as a convenience class.

43 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 43 MyList Interface and MyAbstractList Class MyList MyAbstractList

44 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.

45 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.

46 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.

47 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 47 Implementing MyArrayList MyArrayList Run TestList

48 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.

49 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: class Node { Object element; Node next; public Node(Object o) { element = o; }

50 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;

51 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 51 MyLinkedList

52 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.

53 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.

54 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.

55 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.

56 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.

57 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.

58 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 58 MyStack and MyQueue MyStack MyQueue

59 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

60 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.

61 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.

62 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. class TreeNode { Object element; TreeNode left; TreeNode right; public TreeNode(Object o) { element = o; }

63 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:

64 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.

65 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.

66 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.

67 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

68 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

69 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: F It is a complete binary tree. F Each node is greater than or equal to any of its children.

70 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).

71 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).

72 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 72 Rebuilding a Heap

73 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 73 Removing the Root

74 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 74 Adding a New Node

75 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 75 The Heap Class Heap Run TestHeap

76 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 Run TestPriorityQueue

77 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.

78 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.

79 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.

80 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 80 The Collection Interface The Collection interface is the root interface for manipulating a collection of objects.

81 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.

82 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 82 The Set Interface Hierarchy

83 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.

84 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.

85 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. TestHashSetRun

86 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

87 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. TestLinkedHashSetRun

88 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.

89 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.

90 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

91 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.

92 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.

93 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

94 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.

95 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 95 The List Interface, cont.

96 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 96 The List Iterator

97 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.

98 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 98 LinkedList

99 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. RunTestList

100 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.

101 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.”

102 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 102 The Vector Class, cont.

103 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.

104 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.

105 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. RunFindPrimeUsingVector

106 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.

107 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: RunFindPrimeFactorUsingStack

108 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.

109 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

110 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.

111 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).

112 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. RunTestMap

113 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. RunCountOccurrenceOfWords

114 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.

115 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

116 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. RunTestCollections

117 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.

118 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

119 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. RunTestArrays


Download ppt "Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 BASIC DATA STRUCTURES Chapter."

Similar presentations


Ads by Google