Presentation is loading. Please wait.

Presentation is loading. Please wait.

First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.

Similar presentations


Presentation on theme: "First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types."— Presentation transcript:

1

2 First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.

3 Data Structure Starting Point Any data type that can store more than one value is a data structure.

4 First Array Definition An array is a data structure with one, or more, elements of the same type. A one-dimensional array is frequently also called a vector. A two-dimensional array is frequently also called a matrix.

5 First Record Definition A record is a data structure with one, or more, elements, called fields, of the same or different data types.

6 File Definition A file is an internal data structure - with an unspecified number of elements of the same type - assigned to an external file name. The file data structure allows transfer of data between internal and external storage.

7 Stack Definition A stack is a data structure with elements of the same type. Data elements of the stack data structure can only be accessed (stored or retrieved) at one end of the stack in a LIFO (Last In, First Out) manner.

8 Improved Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types. The storing and retrieval of the data elements is performed by accessing methods that characterize the data structure.

9 Improved Array Definition An array is a data structure with a fixed number of elements of the same type. Every element of the array can be accessed directly.

10 Array Example [16] Ingrid [17] Darlene [18] Gene [19] Sean [20] Stephanie [11] Holly [12] Blake [13] Michelle [14] Remy [15] Haley [06] Diana [07] Jessica [08] David [09] Anthony [10] Alec [01] Isolde [02] John [03] Greg [04] Maria [05] Heidi

11

12 Defining Static Arrays int list[ ]; // declares the array list identifier list = new int[10]; // allocates memory for 10 integers char names[ ]; // declares the names array identifier names = new char[25]; // allocates memory for 25 characters double grades[ ]; // declares the grades array identifier grades = new double[50]; // allocates memory for 50 doubles

13 Defining Static Arrays Preferred Method int list[ ] = new int[10]; char names[ ] = new char[25]; double grades[ ] = new double[50];

14 // Java2601.java // This program demonstrates defining an, and array. // Each array is constructed with default values. public class Java2601 { public static void main(String args[]) { System.out.println("\nJava2601.java\n"); int list1[] = new int[5]; char list2[] = new char[5]; String list3[] = new String[5]; for (int k = 0; k < 5; k++) System.out.println("list1[" + k + "] = " + list1[k]); System.out.println(); for (int k = 0; k < 5; k++) System.out.println("list2[" + k + "] = " + list2[k]); System.out.println(); for (int k = 0; k < 5; k++) System.out.println("list3[" + k + "] = " + list3[k]); System.out.println(); }

15 // Java2602.java // This program initializes three array objects without the operator // by providing a set of initial array element values. public class Java2602 { public static void main(String args[]) { System.out.println("\nJava2602.java\n"); int list1[] = {11,22,33,44,55}; char list2[] = {'A','B','C','D','E'}; String list3[] = {"AAA","BBB","CCC","DDD","EEE"}; for (int k = 0; k < 5; k++) System.out.println("list1[" + k + "] = " + list1[k]); System.out.println(); for (int k = 0; k < 5; k++) System.out.println("list2[" + k + "] = " + list2[k]); System.out.println(); for (int k = 0; k < 5; k++) System.out.println("list3[" + k + "] = " + list3[k]); System.out.println(); }

16 Constructing Java Built-In Arrays Java built-in arrays can be constructed two ways: // array of 5 integers with values automatically initialized to 0. int list[] = new int[5]; // array of 5 integers with 5 initial values of 11, 12, 13, 14, 15. int list[] = {11,12,13,14,15};

17 Arrays Index Range The index of an array starts at 0. The index of the last array element is size-1. An array with 20 elements uses indexes in the range 0..19. An array with n elements uses indexes in the range 0..n-1.

18 // Java2603.java // This program fills an integer array with a random set of numbers. public class Java2603 { public static void main(String args[]) { System.out.println("\nJava2603.java\n"); int list[] = new int[20]; for (int k = 0; k < 20; k++) list[k] = (int) (Math.random() * 900 + 100); for (int k = 0; k < 20; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); }

19 // Java2604.java // This program demonstrates how to pass an array object as a parameter to a method. // It also shows the use of, which stores the size of an array. // length is a public, final object attribute. public class Java2604 { public static void main(String args[]) { System.out.println("\nJava2604.java\n"); int list1[] = {11,22,33,44,55}; int list2[] = {111,222,333,444,555,666,777}; displayList( list1 ); displayList( list2 ); } public static void displayList( int list[ ] ) { for (int k = 0; k < list.length; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); }

20 The length Field Java built-in arrays store the array size in a field called length. This is a public field that can be accessed like list.length The field is final (constant) and cannot be changed. NOTE: Do not confuse the length field of a static array with the length() method of a String.

21

22 2-D Array Example [04][01] Ingrid [04][02] Darlene [04][03] Gene [04][04] Sean [04][05] Stephanie [03][01] Holly [03][02] Blake [03][03] Michelle [03][04] Remy [03][05] Haley [02][01] Diana [02][02] Jessica [02][03] David [02][04] Anthony [02][05] Alec [01][01] Isolde [01][02] John [01][03] Greg [01][04] Maria [01][05] Heidi

23 // Java2605.java // This program demonstrates defining a two-dimensional array with // a consecutive set of integers, and displayed in a matrix format. // It also demonstrates use of the DecimalFormat class. import java.text.DecimalFormat; public class Java2605 { public static void main(String args[]) { System.out.println("\nJava2605.java\n"); DecimalFormat twoDigits = new DecimalFormat("00"); int k = 1; int matrix[][] = new int[7][5]; for (int r = 0; r < 7; r++) for (int c = 0; c < 5; c++) { matrix[r][c] = k; k++; } System.out.println(); for (int r = 0; r < 7; r++) { for (int c = 0; c < 5; c++) System.out.print(twoDigits.format(matrix[r][c]) + " "); System.out.println(); } System.out.println(); }

24 // Java2606.java // This program demonstrates how to use the array attribute with // a two-dimensional array. import java.text.DecimalFormat; public class Java2606 { public static void main(String args[]) { System.out.println("\nJava2606.java\n"); DecimalFormat twoDigits = new DecimalFormat("00"); int k = 1; int matrix[][] = new int[7][5]; for (int r = 0; r < matrix.length ; r++) for (int c = 0; c < matrix[r].length ; c++) { matrix[r][c] = k; k++; } System.out.println(); for (int r = 0; r < matrix.length; r++) { for (int c = 0; c < matrix[c].length; c++) System.out.print(twoDigits.format(matrix[r][c]) + " "); System.out.println(); } System.out.println(); }

25 The length Field for 2-Dimensional Arrays Consider the following statement: int matrix[][] = new int[5][4]; The value of matrix.length is 5. The value of matrix[0].length is 4. The values of matrix[1].length, matrix[2].length, matrix[3].length and matrix[4].length are also 4.

26 // Java2607.java // This program demonstrates how to construct an irregular two-dimensional array // in the shape of a triangle, using a "ragged" array. import java.text.DecimalFormat; public class Java2607 { public static void main(String args[]) { System.out.println("\nJava2607.java\n"); int x[][] = new int[5][ ]; x[0] = new int[1]; x[1] = new int[2]; x[2] = new int[3]; x[3] = new int[4]; x[4] = new int[5]; for (int r = 0; r < x.length; r++) { for (int c = 0; c < x[r].length; c++) System.out.print(x[r][c] + " "); System.out.println(); } System.out.println(); } NOTE: The # of columns is NOT specified.

27 Ragged Arrays Java built-in two-dimensional arrays do not require that every row has the same number of columns. It is allowed to declare an array with an unspecified number of columns in each row using something like new int[5][ ] After that initial construction each row can then be individual constructed with a specified number of columns.

28 Ragged Array Example [06][01] Ingrid [06][02] Darlene [06][03] Gene [06][04] Sean [06][05] Stephanie [05][01] Anthony [05][02] Alec [05][03] Haley [04][01] Holly [04][02] Blake [04][03] Michelle [04][04] Remy [03][01] John [03][02] Greg [03][03] Heidi [03][04] Maria [03][05] David [02][01] Diana [02][02] Jessica [01][01] Isolde NOTE: This is possible because a 2D array is essentially a 1D array of 1D arrays, and each 1D array can be a different size.

29 AP Exam Alert Java built-in one-dimensional and two-dimensional arrays are part of the AP Java subset. Two-dimensional ragged arrays are not part of the AP subset.

30 Program Design Alert Each class in a program should be placed in its own file. Multiple classes are frequently placed in one file throughout this textbook for teaching convenience.

31

32 // Java2608.java // List case study #1 // In stage-1 the class has a constructor method to assign random integers // in a specified range, a method and a method. import java.util.Scanner; public class Java2608 { public static void main(String args[]) { System.out.println("\nJava2608.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List1 array = new List1(listSize,listMin,listMax); array.display(); array.pause(); }

33 class List1 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int minInt; // smallest random integer private int maxInt; // largest random integer public List1(int s, int min, int max) { minInt = min; maxInt = max; size = s; System.out.println("\nCONSTRUCTING LIST WITH VALUES in [" + minInt + ".." + maxInt + "] range"); intArray = new int[size]; int range = maxInt - minInt + 1; for (int k = 0; k < size; k++) intArray[k] = (int) (Math.random() * range + minInt); } public void display() { System.out.println("\nDISPLAYING ARRAY ELEMENTS"); for (int k=0; k < size; k++) System.out.print(intArray[k] + "\t"); System.out.println(); } public void pause() { Scanner input = new Scanner(System.in); String dummy; System.out.print("\nPress to continue ===>> "); dummy = input.nextLine(); }

34

35 // Java2609.java // List case study #2 // In stage-2 the class adds a method. import java.util.Scanner; public class Java2609 { public static void main(String args[]) { System.out.println("\nJava2609.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List2 array = new List2(listSize,listMin,listMax); array.display(); array.pause(); System.out.print("\nEnter search number ===>> "); int searchNumber = input.nextInt(); int index = array.linearSearch(searchNumber); if (index == -1) System.out.println(searchNumber + " is not in the list"); else System.out.println(searchNumber + " is found at index " + index); System.out.println(); }

36 class List2 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int minInt; // smallest random integer private int maxInt; // largest random integer public List2(int s, int min, int max) // same as before public void display()// same as before public void pause() // same as before public int linearSearch(int sn) { boolean found = false; int k = 0; while (k < size && !found) { if (intArray[k] == sn) found = true; else k++; } if (found) return k; else return -1; }

37

38 Bubble Sort Logic Compare adjacent array elements. Swap the elements if they are not ordered correctly. Continue this process until the largest element is in the last element of the array. Repeat the comparison process in the same manner. During the second pass make one less comparison, and place the second-largest number in the second-to-last element of the array. Repeat these comparison passes with n elements, n-1 times. Each pass makes one less comparison.

39 // Java2610.java // List case study #3 // In stage-3 the method is added to the class. import java.util.Scanner; public class Java2610 { public static void main(String args[]) { System.out.println("\nJava2610.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List3 array = new List3(listSize,listMin,listMax); array.display(); array.pause(); array.bubbleSort(); array.display(); array.pause(); }

40 class List3 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int minInt; // smallest random integer private int maxInt; // largest random integer public List3(int s, int min, int max) // same as before public void display()// same as before public void pause() // same as before public void bubbleSort() { int temp; for (int p = 1; p < size; p++) for (int q = 0; q < size-p; q++) if (intArray[q] > intArray[q+1]) { temp = intArray[q]; intArray[q] = intArray[q+1]; intArray[q+1] = temp; }

41

42 // Java2611.java // List case study #4 // In Stage-4 the is improved to exit when the array list is sorted and // a private method is added. import java.util.Scanner; public class Java2611 { public static void main(String args[]) { System.out.println("\nJava2611.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt();; System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List4 array = new List4(listSize,listMin,listMax); array.display(); array.pause(); array.bubbleSort(); array.display(); array.pause(); }

43 class List4 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int minInt; // smallest random integer private int maxInt; // largest random integer public List3(int s, int min, int max) // same as before public void display()// same as before public void pause() // same as before private void swap(int x, int y) { int temp = intArray[x]; intArray[x] = intArray[y]; intArray[y] = temp; } public void bubbleSort() { boolean sorted; int p = 1; do { sorted = true; for (int q = 0; q < size-p; q++) if (intArray[q] > intArray[q+1]) { swap(q,q+1); sorted = false; } p++; } while (!sorted); }

44

45 Inserting an Element into an Array - Step 1 [0][1][2][3][4][5][6][7][8][9][10][11][12] 15182327293245527475899093

46 Inserting an Element into an Array - Step 2 [0][1][2][3][4][5][6][7][8][9][10][11][12] 15182327293245527475899093

47 Inserting an Element into an Array - Step 3 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 15182327293245527475899093

48 Inserting an Element into an Array - Step 4 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 151823272932455274 75899093

49 Inserting an Element into an Array - Step 5 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

50 // Java2612.java // List case study #5 // Stage-5 adds the Insert algorithm and the constructor is altered to // instantiate an array object twice the requested size to allow for expansion. import java.util.Scanner; public class Java2612 { public static void main(String args[]) { System.out.println("\nJava2612.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List5 array = new List5(listSize,listMin,listMax); array.display(); array.pause(); array.bubbleSort(); array.display(); array.pause(); System.out.print("\nEnter insert number ===>> "); int insertNumber = input.nextInt(); array.insert(insertNumber); array.display(); array.pause(); }

51 class List5 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int capacity; // actual storage space of intArray private int minInt; // smallest random integer private int maxInt; // largest random integer public List5(int s, int min, int max) { minInt = min; maxInt = max; size = s; capacity = 2 * size; System.out.println("\nCONSTRUCTING LIST WITH VALUES in [" + minInt + ".." + maxInt + "] range"); intArray = new int[capacity]; int range = maxInt - minInt + 1; for (int k = 0; k < size; k++) intArray[k] = (int) (Math.random() * range + minInt); } public void insert(int insertNum) { int index = 0; while (index intArray[index]) index++; size++; if (size > capacity) System.out.println("Insertion aborted; insufficient capacity"); else { for (int k = size-1; k > index; k--) intArray[k] = intArray[k-1]; intArray[index] = insertNum; }

52

53 Searching Notes The searches used for a deletion and insertion algorithms are not the same. A search used for a deletion algorithm must find a match with an existing element. Without such a match, deletion is not a possibility. A search used for an insertion algorithm only needs to find a location between existing elements. There is always a location that can be found to insert a new element.

54 Deleting an Element from an Array - Step 1 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

55 Deleting an Element from an Array - Step 2 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

56 Deleting an Element from an Array - Step 3 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 15182327293245527475899093

57 Deleting an Element from an Array - Step 4 [0][1][2][3][4][5][6][7][8][9][10][11][12] 15182327293245527475899093

58 // Java2613.java // List case study #6 // Stage-6 adds the "delete" algorithm to the List class. import java.util.Scanner; public class Java2613 { public static void main(String args[]) { System.out.println("\nJava2613.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List6 array = new List6(listSize,listMin,listMax); array.display(); array.pause(); array.bubbleSort(); array.display(); array.pause(); System.out.print("\nEnter delete number ===>> "); int deleteNumber = input.nextInt(); array.delete(deleteNumber); array.display(); array.pause(); }

59

60

61 Selection Sort Logic Set the first number as the smallest number. Compare the smallest number to each number in the list. If any number is smaller, it becomes the smallest number. After every number is compared, swap the smallest number with the first number. The smallest number is now in the correct location. Repeat the comparison process in the same manner. During the second pass, start with the second number and make it the smallest number. At the conclusion of the comparison pass swap the smallest number with the second number. Repeat these comparison passes with n elements, n-1 times. Each pass makes one less comparison.

62 // Java2614.java // List case study #7 // This stage replaces the Bubble Sort with the Selection Sort. import java.util.Scanner; public class Java2614 { public static void main(String args[]) { System.out.println("\nJava2614.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List7 array = new List7(listSize,listMin,listMax); array.display(); array.pause(); array.selectionSort(); array.display(); array.pause(); }

63 class List7 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int minInt; // smallest random integer private int maxInt; // largest random integer private void swap(int x, int y) { int temp = intArray[x]; intArray[x] = intArray[y]; intArray[y] = temp; } public void selectionSort() { for (int p = 0; p < size-1; p++) { int smallest = p; for (int q = p+1; q < size; q++) if (intArray[q] < intArray[smallest]) smallest = q; if (intArray[p] != intArray[smallest]) swap(p,smallest); }

64

65 Binary Search with a Telephone Book Start with a 2000 page telephone book. Split in two, and ignore 1000 pages and search in the remaining 1000 pages. Split in two, and ignore 500 pages and search in the remaining 500 pages. Split in two, and ignore 250 pages and search in the remaining 250 pages. Split in two, and ignore 125 pages and search in the remaining 125 pages. Split in two, and ignore 62 pages and search in the remaining 62 pages. Split in two, and ignore 31 pages and search in the remaining 31 pages. Split in two, and ignore 15 pages and search in the remaining 15 pages. Split in two, and ignore 7 pages and search in the remaining 7 pages. Split in two, and ignore 3 pages and search in the remaining 3 pages. Split in two, and ignore 1 page and search in the remaining 1 page.

66 Binary Search Logic The Binary Search only works with sorted lists. Start by making the smallest index small and the largest index large. Find the midpoint index with (small + large) / 2 Compare the midpoint value with the search item. If the value is found you are done. Otherwise re-assign small or large. If the search item is greater you have a new small, otherwise you have a new large Repeat the same process. Continue the process until the search item is found or large becomes less than small.

67 Using the Binary Search to Find an Element in an Array Step 1 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

68 Using the Binary Search to Find an Element in an Array Step 2 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

69 Using the Binary Search to Find an Element in an Array Step 3 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

70 Using the Binary Search to Find an Element in an Array Step 4 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

71 Using the Binary Search to Find an Element in an Array Step 5 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

72 Using the Binary Search to Find an Element in an Array Step 6 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

73 Using the Binary Search to Find an Element in an Array Step 7 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

74 Using the Binary Search to Find an Element in an Array Step 8 [0][1][2][3][4][5][6][7][8][9][10][11][12][13] 1518232729324552607475899093

75 // Java2615.java // List case study #8 // This program introduces the method, which searches a sorted list // far more efficiently than the earlier method. import java.util.Scanner; public class Java2615 { public static void main(String args[]) { System.out.println("\nJava2615.java\n"); Scanner input = new Scanner(System.in); System.out.print("\nEnter list size ===>> "); int listSize = input.nextInt(); System.out.print("Enter minimum value ===>> "); int listMin = input.nextInt(); System.out.print("Enter maximum value ===>> "); int listMax = input.nextInt(); List8 array = new List8(listSize,listMin,listMax); array.display(); array.pause(); array.selectionSort(); array.display(); array.pause(); System.out.print("\nEnter search number ===>> "); int searchNumber = input.nextInt(); int index = array.binarySearch(searchNumber); if (index == -1) System.out.println(searchNumber + " is not in the list"); else System.out.println(searchNumber + " is located at index " + index); System.out.println(); }

76 class List8 { private int intArray[];// stores aray elements private int size; // number of elements in the array private int minInt; // smallest random integer private int maxInt; // largest random integer public int binarySearch(int sn) { boolean found = false; int lo = 0; int hi = size-1; int mid = 0; while (lo <= hi && !found) { mid = (lo + hi) / 2; if (intArray[mid] == sn) found = true; else { if (sn > intArray[mid]) lo = mid+1; else hi = mid-1; } if (found) return mid; else return -1; }

77

78

79 // Java2616.java List case study #9 // In the final stage of the List casestudy, the list is now an array of // Student objects. Note how the sort method compares according to GPAs. import java.io.*; public class Java2616 { public static void main(String args[]) throws IOException { System.out.println("\nJava2616.java\n"); List9 studentArray = new List9(100); studentArray.getList(); studentArray.display(); studentArray.pause(); studentArray.bubbleSort(); studentArray.display(); studentArray.pause(); } class Person { private String name; private int age; private double gpa; Person(String n,int a,double g){ name = n; age = a; gpa = g; } public String getName(){ return name; } public int getAge() { return age; } public double getGPA() { return gpa; } }

80 class List9 { private Person student[];// stores array elements private int capacity; // actual array capacity private int size; // number of elements in the array public List9(int c) { capacity = c; size = 0; student = new Person[capacity]; } public void getList() throws IOException { FileReader inFile = new FileReader("Students.dat"); BufferedReader inStream = new BufferedReader(inFile); String s1,s2,s3; int index = 0; while( ((s1 = inStream.readLine()) != null) && ((s2 = inStream.readLine()) != null) && ((s3 = inStream.readLine()) != null) ) { String name = s1; int age = Integer.parseInt(s2); double gpa = Double.parseDouble(s3); student[index] = new Person(name,age,gpa); index++; } inStream.close(); size = index; }

81 public void display() { System.out.println("\nDISPLAYING ARRAY ELEMENTS"); for (int k = 0; k < size; k++) System.out.println(student[k].getName() + "\t\t" + student[k].getAge() + "\t\t" + student[k].getGPA() ); } public void pause() { Scanner input = new Scanner(System.in); String dummy; System.out.print("\nPress to continue ===>> "); dummy = input.nextLine(); } public void bubbleSort() { for (int p = 1; p < size; p++) for (int q = 0; q < size-p; q++) if (student[q].getGPA() < student[q+1].getGPA()) swap(q,q+1); }

82

83

84 // Java2617.java // This program introduces the class along with the method // to add additional elements to the end of the list, the method for // the number of array elements and the method to retrieve ArrayList elements. // Note that it is possible to display ArrayList elements directly. import java.util.ArrayList; public class Java2617 { public static void main(String args[]) { System.out.println("\nJava2617.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add(new String("Heidi")); for (int k = 0; k < names.size(); k++) System.out.println( names.get(k) ); System.out.println(); System.out.println("names contains " + names); System.out.println(); }

85 ArrayList Methods add & get names.add("Tom"); System.out.println(names.get(3)); The add method allocates spaces for the newly enlarged array and then stores the new array element at the end of the ArrayList object. The get method accesses a specified array element. The parameter of the get method is the index of the ArrayList object and starts at 0.

86 ArrayList size Method for (int k = 0; k < names.size(); k++) The size method will tell you how many elements are in the ArrayList object. NOTE: Do NOT confuse the size() method of the ArrayList class with the length() method of the String class or the length field of a Java Static Array.

87 // Java2618.java // This program demonstrates the method of the class, which // replaces existing elements with a new object. import java.util.ArrayList; public class Java2618 { public static void main(String args[]) { System.out.println("\nJava2618.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); names.set(1,"Jessica"); names.set(3,"Anthony"); names.set(4,"Haley"); System.out.println("names contains " + names); System.out.println(); }

88 ArrayList set Method names.set(4,"Tom"); The set method uses the first parameter as the index location to find an array element and then replaces it with the value of the second set parameter. You will get an error if you try to access an index location, which has not been allocated yet.

89 // Java2619.java // This program demonstrates the method of the class to // delete a specified list element. import java.util.ArrayList; public class Java2619 { public static void main(String args[]) { System.out.println("\nJava2619.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); names.remove(2); System.out.println("names contains " + names); System.out.println(); }

90 ArrayList remove Method names.remove(3); The remove method removes the array element at the index location of its parameter and decreases the object size by one array element. You will get an error if you try to access an index location, which does not exist.

91 // Java2620.java // This program demonstrates how to use the method of the class to // insert new elements at a specified location, the method to remove // all the list elements and the method to check list emptyness. import java.util.ArrayList; public class Java2620 { public static void main(String args[]) { System.out.println("\nJava2620.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); names.add(3,"Anthony"); System.out.println("names contains " + names); System.out.println("Number of names elements: " + names.size()); System.out.println(); names.clear(); System.out.println("Number of names elements: " + names.size()); if ( names.isEmpty() ) System.out.println("The list is empty"); else System.out.println("The list is not empty"); System.out.println(); }

92 ArrayList Methods add, clear & isEmpty names.add(3,"Kathy"); names.clear(); if (names.isEmpty()) The overloaded add(3,"Kathy") method adds or rather inserts a new array element at the indicated index. The clear method removes all array elements and returns all previously allocated space back to memory. The isEmpty method returns true if the names object is empty and returns false otherwise.

93 // Java2621.java // This program demonstrates how to make a copy of an object with the method. import java.util.ArrayList; public class Java2621 { public static void main(String args[]) { System.out.println("\nJava2621.java\n"); ArrayList names1 = new ArrayList(); names1.add("Isolde"); names1.add("John"); names1.add("Greg"); names1.add("Maria"); names1.add("Heidi"); System.out.println("names1 contains " + names1); System.out.println(); ArrayList names2 = (ArrayList) names1.clone(); System.out.println("names2 contains " + names2); System.out.println(); }

94 // Java2622.java // This program demonstrates that it is possible to store integers in an // object with the class. It is easier to use a regular array to store // primitive data elements. import java.util.ArrayList; public class Java2622 { public static void main(String args[]) { System.out.println("\nJava2622.java\n"); ArrayList numbers = new ArrayList(); numbers.add(new Integer(12345)); numbers.add(new Integer(23451)); numbers.add(new Integer(34512)); numbers.add(new Integer(45123)); numbers.add(new Integer(51234)); System.out.println("numbers contains " + numbers); System.out.println(); }

95 // Java2623.java // This program demonstrates that it is possible to store doubles and booleans in an // object with the and classes. It also shows that an // ArrayList can store different object types in the same array. import java.util.ArrayList; public class Java2623 { public static void main(String args[]) { System.out.println("\nJava2623.java\n"); ArrayList misc = new ArrayList(); misc.add(new Double(12.345)); misc.add(new Double(23.451)); misc.add(new Double(34.512)); misc.add(new Double(45.123)); misc.add(new Double(51.234)); misc.add(new Boolean(true)); misc.add(new Boolean(false)); System.out.println("misc contains " + misc); System.out.println(); }

96 Hey, wait a minute! Did we not see earlier the following definition of an array: Actually, the definition is still correct. The ArrayList in the previous program did not actually store doubles and booleans. It stored the memory addresses of objects. So every index of an ArrayList does store the same type. The actual data located at the memory referenced locations can be of any type. An array is a data structure with a fixed number of elements of the same type.

97 // Java2624.java // This program attempts to compute the sum of the Integer objects in the ArrayList. // While Integer objects can be stored and displayed, they cannot be added. import java.util.Random; import java.util.ArrayList; public class Java2624 { public static void main (String args[]) { System.out.println("\nJava2624.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); int j; for(j = 0; j < 20; j++) numbers.add( new Integer(rand.nextInt(90) + 10) ); System.out.println(numbers+"\n"); int sum = 0; for(j = 0; j < 20; j++) sum += numbers.get( j ); System.out.println("sum: " + sum); System.out.println(); }

98 // Java2625.java // This program properly adds up the Integers in the ArrayList by first converting // them to ints with the intValue method. NOTE: Typecasting is required. import java.util.Random; import java.util.ArrayList; public class Java2625 { public static void main (String args[]) { System.out.println("\nJava2625.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); int j; for(j = 0; j < 20; j++) numbers.add( new Integer(rand.nextInt(90) + 10) ); System.out.println(numbers+"\n"); int sum = 0; for(j = 0; j < 20; j++) { Integer num = (Integer) numbers.get( j ); sum += num.intValue(); } System.out.println("sum: " + sum); System.out.println(); }

99 // Java2626.java // This program demonstrates the doubleValue and booleanValue methods by // adding every other real number in the numbers ArrayList by using the // evens ArrayList. NOTE: Class casting is still required. import java.util.Random; import java.util.ArrayList; public class Java2626 { public static void main (String args[]) { System.out.println("\nJava2626.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); ArrayList evens = new ArrayList(); int j; boolean temp = true; for(j = 0; j < 10; j++) { numbers.add( new Double( Math.floor(rand.nextDouble() * 100000) / 100 )); evens.add( new Boolean(temp) ); temp = !temp; }

100 System.out.println(); System.out.println(numbers); System.out.println(evens); System.out.println(); double sum = 0.0; for(j = 0; j < 10; j++) { Boolean even1 = (Boolean) evens.get(j); boolean even2 = even1.booleanValue(); if (even2) { Double num = (Double) numbers.get(j); sum += num.doubleValue(); } System.out.println("sum: " + sum); System.out.println(); }

101 ArrayList Elements All ArrayList elements must be objects. Storing primitive types like int s in an ArrayList object requires that the primitive type is converted into an object first with a statement like: numbers.add(new Integer(51234)); Accessing the values of a primitive data type wrapped inside an object requires typecasting and a conversion method like intValue(), doubleValue(), or booleanValue().

102 // Java2627.java // This program takes the earlier Java2616.java program, implemented with // a array, and converts it to an implementation. import java.io.*; import java.util.Scanner; import java.util.ArrayList; public class Java2627 { public static void main(String args[]) throws IOException { System.out.println("\nJava2627.java\n"); List10 array = new List10(); array.getList(); array.display(); array.pause(); array.bubbleSort(); array.display(); } class Person { public String name; public int age; public double gpa; Person(String n,int a,double g) { name = n; age = a; gpa = g; } }

103 class List10 { private ArrayList students; public List10() { students = new ArrayList(); } public void getList() throws IOException { FileReader inFile = new FileReader("Students.dat"); BufferedReader inStream = new BufferedReader(inFile); String s1,s2,s3; while( ((s1 = inStream.readLine()) != null) && ((s2 = inStream.readLine()) != null) && ((s3 = inStream.readLine()) != null) ) { String name = s1; int age = Integer.parseInt(s2); double gpa = Double.parseDouble(s3); students.add(new Person(name,age,gpa)); } inStream.close(); }

104 public void display() { System.out.println("\nDISPLAYING LIST ELEMENTS"); for (int k = 0; k < students.size(); k++) { Person p = (Person) students.get(k); System.out.println(p.name + "\t\t" + p.age + "\t\t" + p.gpa); } public void pause() { Scanner input = new Scanner(System.in); String dummy; System.out.print("\nPress to continue ===>> "); dummy = input.nextLine(); }

105 private void swap(int x, int y) { Person temp = (Person) students.get(x); students.set(x,students.get(y)); students.set(y,temp); } public void bubbleSort() { Person person1,person2; for (int p = 1; p < students.size(); p++) for (int q = 0; q < students.size()-1; q++) { person1 = (Person) students.get(q); person2 = (Person) students.get(q+1); if (person1.gpa < person2.gpa) swap(q,q+1); }

106

107

108 Are Strings arrays of characters? In many programming languages if you have something like: String name = "Jessica"; you could use the index[ ] operator to access this individual characters in the String in this way: System.out.println(name[0]);

109 // Java2628.java // In many languages a String is an array of characters. // This program shows that is NOT true in Java. public class Java2628 { public static void main(String args[]) { System.out.println("\nJava2628.java\n"); String s = "discombobulated"; System.out.println(s); for (int j = s.length()-1; j >= 0; j--) System.out.print(s[ j ]); System.out.println("\n\n"); } This error message makes it clear that in Java, a String is NOT an array of characters.

110 // Java2629.java // While a Java String is NOT an array of characters, it is possible // to access the individual characters in the string. This program // used the charAt method to display a String backwards. public class Java2629 { public static void main(String args[]) { System.out.println("\nJava2629.java\n"); String s = "discombobulated"; System.out.println(s); for (int j = s.length()-1; j >= 0; j--) System.out.print(s.charAt( j )); System.out.println("\n\n"); }

111 String method charAt In many computer languages, Strings are arrays of characters and the individual characters can be accessed with the index operator. String name = “Jessica”; System.out.println(s[0]); // This will NOT compile. This however is NOT true in Java. In Java, Strings are objects. Even so, the individual characters can be accessed with the charAt method. String name = “Jessica”; System.out.println(name.charAt(0)); // This will print ‘J’.

112

113

114 // Java2630.java // This program introduces the Java 5.0 enhanced loop // with an array. public class Java2630 { public static void main(String args[]) { System.out.println("Java2630\n"); int list[] = {11,22,33,44,55,66,77,88,99}; ///// JAVA 1.4 ///// for (int k = 0; k loop syntax System.out.print(list[k] + " "); System.out.println("\n\n"); ///// JAVA 5.0 ///// for (int item: list)// New loop syntax System.out.print(item + " "); System.out.println("\n\n"); }

115 // Java2631.java // This program uses the Java5.0 loop with a array. public class Java2631 { public static void main(String args[]) { System.out.println("Java2631.java\n"); String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"}; ///// JAVA 1.4 ///// for (int k = 0; k loop syntax System.out.print(names[k] + " "); System.out.println("\n\n"); ///// JAVA 5.0 ///// for (String name: names)// New loop syntax System.out.print(name + " "); System.out.println("\n\n"); }

116 // Java2632.java // This program uses the Java5.0 loop with an object. import java.util.*; public class Java2632 { public static void main(String args[]) { System.out.println("Java2632.java\n"); ArrayList names = new ArrayList(); names.add("Tom"); names.add("Sue"); names.add("Joe");names.add("Jan");names.add("Bob"); ///// JAVA 1.4 ///// for (int k = 0; k loop syntax System.out.print(names.get(k) + " "); System.out.println("\n\n"); ///// JAVA 5.0 ///// for (Object name: names)// New loop syntax System.out.print(name + " "); System.out.println("\n\n"); }

117 Java 5.0 Enhanced for Loop The enhanced for loop is called the "for.. each" loop. The new loop structure does not replace the older for loop, because it is NOT possible to access or alter specific array elements. int numbers[ ] = {1,2,3,4,5,6,7,8,9}; for (int number: numbers) System.out.prin t(number + " ");

118

119 // Java2633.java // This program introduces automatic "boxing" and "unboxing". // In this example the simple values are automatically converted // to objects and objects are converted to values. public class Java2633 { public static void main (String args[]) { System.out.println(); System.out.println("Java2633.java\n"); ///// JAVA 1.4 ///// Integer num1 = new Integer(200); // boxes or wraps value 200 inside an object int num2 = num1.intValue(); // unboxes or unwraps the object into an 200 value System.out.println("num1 = " + num1); System.out.println(); ///// JAVA 5.0 ///// Integer num3 = 400; // automatically boxes 400 inside an object int num4 = num3; // automatically unboxes object into an 400 value System.out.println("num4 = " + num4); System.out.println("\n\n"); }

120 Autoboxing Observation ArrayList objects cannot store primitive data values, even if it appears that int values are added directly to an ArrayList object. With Java 5.0 the required boxing and unboxing are done automatically.

121 // Java2634.java This program shows a practical example of "autoboxing". // Note how it is easier to add simple values to an object. import java.util.*;// necessary to use the class. public class Java2634 { public static void main (String args[]) { System.out.println(); System.out.println("Java2634.java\n"); ArrayList list = new ArrayList(); ///// JAVA 1.4 ///// list.add(new Integer(100)); list.add(new Integer(200)); list.add(new Integer(300)); System.out.println(list); ///// JAVA 5.0 ///// list.add(400); list.add(500); list.add(600); System.out.println(list); System.out.println("\n\n"); }

122 // Java2635.java // This program shows that automatic "unboxing" with objects still requires the need for // casting. There is no automatic assumption that an object stores an. import java.util.*;// necessary to use the class. public class Java2635 { public static void main (String args[]) { System.out.println(); System.out.println("Java2635.java\n"); ArrayList list = new ArrayList(); ///// JAVA 1.4 ///// list.add(new Integer(100)); list.add(new Integer(200)); list.add(new Integer(300)); System.out.println(list); int num1 = ((Integer)list.get(2)).intValue(); System.out.println("num1 = " + num1); System.out.println("\n\n"); ///// JAVA 5.0 ///// list.add(400); list.add(500); list.add(600); System.out.println(list); int num2 = ((Integer)list.get(4)); // is not necessary, but casting is System.out.println("num2 = " + num2); System.out.println("\n\n"); }

123

124 // Java2636.java This program repeats the Java2635.java example. // This time typecasting is not necessary in line 31. import java.util.*;// necessary to use the class. public class 2636 { public static void main (String args[]) { System.out.println(); System.out.println("Java2636.java\n"); ///// JAVA 1.4 ///// ArrayList list1 = new ArrayList(); list1.add(new Integer(100)); list1.add(new Integer(200)); list1.add(new Integer(300)); System.out.println(list1); int num1 = ((Integer)list1.get(2)).intValue(); System.out.println("num1 = " + num1); System.out.println("\n\n"); ///// JAVA 5.0 ///// ArrayList list2 = new ArrayList (); // Note that is specified list2.add(400); list2.add(500); list2.add(600); System.out.println(list2); int num2 = list2.get(2);// type casting is not necessary with generics System.out.println("num2 = " + num2); System.out.println("\n\n"); }

125 // Java2637.java // This program introduces the concept of a templated class. In this example you will observe that // three objects are instantiated with three different object types. import java.util.*;// necessary to use the class. public class Java2637 { public static void main (String args[]) { System.out.println(); System.out.println("Java2637.java\n"); ///// JAVA 1.4 ///// ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); ArrayList list3 = new ArrayList(); list1.add(new Integer(100)); list2.add(new Double(200.123)); list3.add("Generics"); int val1 = ((Integer)list1.get(0)).intValue(); double val2 = ((Double)list2.get(0)).doubleValue(); String val3 = ((String)list3.get(0)); System.out.println(val1 + "\n" + val2 + "\n" + val3 +"\n\n"); ///// JAVA 5.0 ///// ArrayList list4 = new ArrayList (); ArrayList list5 = new ArrayList (); ArrayList list6 = new ArrayList (); list4.add(100); list5.add(200.123); list6.add("Generics"); int val4 = list4.get(0); double val5 = list5.get(0); String val6 = list6.get(0); System.out.println(val4 + "\n" + val5 + "\n" + val6 +"\n\n"); }


Download ppt "First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types."

Similar presentations


Ads by Google