Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7 Arrays and Array Lists. Assignment: Read lessons 7.1 thru 7.8, take notes, and complete the self- check questions in your notebook Written exercises:

Similar presentations


Presentation on theme: "Chapter 7 Arrays and Array Lists. Assignment: Read lessons 7.1 thru 7.8, take notes, and complete the self- check questions in your notebook Written exercises:"— Presentation transcript:

1 Chapter 7 Arrays and Array Lists

2 Assignment: Read lessons 7.1 thru 7.8, take notes, and complete the self- check questions in your notebook Written exercises: R7.1, 7.3, 7.4,7.6 – 7.7 R7.11, 7.12, 7.16 – Due December 9, 2013 Programming exercises P7.2 – 7.6, 7.9, 7.10, Due December 17, 2013 – For 7.2 – 7.6 You may write one long program that includes each modification to your Purse Class. Comment each method as 7.2, or 7.3, or 7.4 …etc. – Work with one other person and submit one final copy of the all programs to the completed works folder. FunNumber2 exercises – due December 20, 2013

3 Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized for loop To study common array algorithms Continued…

4 Chapter Goals To learn how to use two-dimensional arrays To understand when to choose array lists and arrays in your programs To implement partially filled arrays

5 Arrays An array is a fixed-length sequence of values of the same type. You access array elements with an integer index, using the notation a[i]. The number of elements an array can hold is accessed by using the length field of the array: a.length. (notice no () after length, because it is a public final field) Arrays can hold primitive values or objects.

6 Arrays Construct array: Store in variable of type double[ ] Find Length of an array new double[10] double[] data = new double[10]; Continued… System.out.println (data.length);

7 Arrays Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array.

8 Arrays Note that length is the number of elements the array can hold….not the number of positions filled. int[] a = new int[5]; a[0] = 78; a[1] = 89; for (int x = 0; x < a.length ; x++) { System.out.print("\t"+ a[x] + "\t"); } prints:

9 Arrays When array is created, all values are initialized depending on array type: – Numbers: 0 – Boolean: false – Object References: null

10 Arrays Figure 1: An Array Reference and an Array

11 Arrays Use [ ] to access an element Figure 2: Storing a Value in an Array data[2] = 29.95;

12 Arrays Using the value stored: Get array length as data.length. (Not a method!) Index values range from 0 to (length - 1 ) System.out.println("The value of this data item is " + data[4]); Continued… Array Name

13 Arrays Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array. // filling array from input import java.util.Scaner; … scanner in = new Scanner(System.in); int count = 0; boolean done = false; int maxCount = 10; int[] arr = new int[maxCount]; while(count < maxCount && !done) { System.out.println("Enter integer (-1 to quit.): "); int a = in.nextInt(); if (a != -1) { arr[count] = a; count++; } else done = true; } size = count; // Remember number of filled // elements }

14 Arrays Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array and carry it around with you! public static void listForward(int[] tList, int num) { for (int x = 0; x < num ; x++) { System.out.print("\t"+ tList[x] + "\t"); } System.out.println(); }

15 Arrays Accessing a nonexistent element results in a bounds error Limitation: Arrays have fixed length double[] data = new double[10]; data[10] = 29.95; // ERROR

16 Self Check 1.What elements does the data array contain after the following statements? Ans: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not 100 double[] data = new double[10]; for (int i = 0; i < data.length; i++) data[i] = i * i;

17 Self Check 2.What do the following program segments print? Or, if there is an error, describe the error and specify whether it is detected at compile-time or at run-time a runtime error: array index out of bounds 3. a compile-time error: c is not initialized 1. double[] a = new double[10]; System.out.println(a[0]); 2. double[] b = new double[10]; System.out.println(b[10]); 3. double[] c; System.out.println(c[0]);

18 Copying Arrays: Copying Array References Copying an array variable yields a second reference to the same array double[] data = new double[10]; // fill array... double[] prices = data; Continued…

19 Copying Arrays: Copying Array References Figure 7: Two References to the Same Array

20 Copying Arrays: Cloning Arrays Use clone to make true copy double[] prices = (double[]) data.clone(); Continued… Need to cast as a (double) since cloned type is an Object

21 Copying Arrays: Cloning Arrays Figure 8: Cloning an Array

22 Copying Arrays: Copying Array Elements Continued… System.arraycopy(from, fromStart, to, toStart, count); From Array Name To Array Name How many elements to copy

23 Copying Arrays: Copying Array Elements Figure 9: The System. arraycopy Method

24 Arrays Now, what if you run out of room? You must allocate a larger array and copy the elements from the original array to the larger array.

25 Growing an Array If the array is full and you need more space, you can grow the array: 1.Create a new, larger array. 2.Copy all elements into the new array 3.Store the reference to the new array in the array variable double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

26 Arrays You must allocate a larger array and copy the elements from the original array to the larger array. data newData free space By setting data = newData the array data now references the copy.

27 Growing an Array Figure 12: Growing an Array

28 Sample Code You must allocate a larger array and copy the elements from the original array to the larger array. int[] copyOfArray = new int[2* arr.length]; for (int i = 0; i < arr.length; i++) { copyOfArray[i] = arr[i]; } arr = copyOfArray;

29 Simple Array Algorithms: Finding the Maximum or Minimum Steps -- Ex.  Find the largest bank acct balance 1.Initialize a candidate with the starting element 2.Compare candidate with remaining elements 3.Update it if you find a larger or smaller value Continued…

30 Simple Array Algorithms: Finding the Maximum or Minimum Example: BankAccount largestYet = accounts[0]; for (int i = 1; i largestYet.getBalance()) largestYet = a; } return largestYet;

31 Filling an Array using an initializer list: Instead of: int[] primes = new int[3]; primes[0] = 2; primes[1] = 3; primes[2] = 5; Use: int[]primes = {2, 3, 5};

32 Arrays It is not very convenient to track array sizes and to grow arrays when they run out of space. – If you are collecting objects, use ArrayList. – If you collect numbers, you must make a choice. Which is the least inconvenient? Using wrapper classes? Tracking array size?

33 Dr. Seuss: "Too Many Daves" Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave? Well, she did. And that wasn't a smart thing to do. You see, when she wants one, and calls out "Yoo-Hoo! Come into the house, Dave!" she doesn't get one. All twenty-three Daves of hers come on the run!

34 This makes things quite difficult at the McCaves' As you can imagine, with so many Daves. And often she wishes that, when they were born, She had named one of them Bodkin Van Horn. And one of them Hoos-Foos. And one of them Snimm. And one of them Hot-Shot. And one Sunny Jim. Another one Putt-Putt. Another one Moon Face. Another one Marvin O'Gravel Balloon Face. And one of them Zanzibar Buck-Buck McFate... But she didn't do it. And now it's too late. "Too Many Daves"

35 This is not all that bad….. Come into the house, Dave!" she doesn't get one. All twenty-three Daves of hers come on the run!

36 ArrayList It is very common for applications to require us to store a large amount of data. Array Lists store large amounts of data in a single collection that can be referred to with a single variable.

37 ArrayList An ArrayList is a sequence of objects that grows and shrinks as needed. The ArrayList class is part of the java.util package of the Java standard class library.

38 ArrayList Each element in the sequence can be accessed separately. We can explicitly overwrite an object at a specified position in the sequence, thus changing its value. We can inspect the object at a specified location in the sequence.

39 ArrayList We can add an object into a specified position of the sequence. We can add an object to the end of the sequence. We can remove an object from a specified location in the sequence.

40 ArrayList methods: boolean add(Object x) // appends x to the end of list; returns true int size() // returns the number of elements in this list Object get(int index) // returns the element at the specified position in this list. Object set(int index, Object x) // replaces the element at index with x // returns the element formerly at the specified position Iterator iterator() //Returns an iterator over the elements in the arraylist in proper sequence. ListIterator listIterator() //Returns a list iterator over the elements in this arraylist (in proper sequence). Use to traverse through the list – iterators point between two elements in the list.

41 More ArrayList methods void add(int index, Object x) // inserts x at position index, sliding elements // at position index and higher to the right // (adds 1 to their indices) and adjusts size Object remove(int index) // removes element from position index, sliding // subsequent elements to the left (subtracts 1 from their //indices) and adjusts size // returns the element at the specified position in this list.

42 Array Lists The ArrayList class is a generic class: ArrayList collects objects of type T : size method yields number of elements ArrayList accounts = new ArrayList (); accounts.add(new BankAccount(1001)); accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1022));

43 Retrieving Array List Elements Use get method Index starts at 0 Bounds error if index is out of range BankAccount anAccount = accounts.get(2); // gets the third element of the array list Continued…

44 Retrieving Array List Elements Most common bounds error: int i = accounts.size(); anAccount = accounts.get(i); // Error // legal index values are 0...i-1 Since positions start at zero

45 Adding Elements set overwrites an existing value add adds a new value before the index Continued… BankAccount anAccount = new BankAccount(1729); accounts.set(2, anAccount); accounts.add(i, a)

46 Adding Elements Figure 3: Adding an Element in the Middle of an Array List

47 Removing Elements remove removes an element at an index Continued… Accounts.remove(i)

48 Removing Elements Figure 4: Removing an Element in the Middle of an Array List

49 File: ArrayListTester.java - p : import java.util.ArrayList; 02: 03: /** 04: This program tests the ArrayList class. 05: */ 06: public class ArrayListTester 07: { 08: public static void main(String[] args) 09: { 10: ArrayList accounts 11: = new ArrayList (); 12: accounts.add(new BankAccount(1001)); 13: accounts.add(new BankAccount(1015)); 14: accounts.add(new BankAccount(1729)); 15: accounts.add(1, new BankAccount(1008)); 16: accounts.remove(0); Continued…

50 File: ArrayListTester.java 17: 18: System.out.println("size=" + accounts.size()); 19: BankAccount first = accounts.get(0); 20: System.out.println("first account number=" 21: + first.getAccountNumber()); 22: BankAccount last = accounts.get(accounts.size() - 1); 23: System.out.println("last account number=" 24: + last.getAccountNumber()); 25: } 26: } Output size=3 first account number=1008 last account number=1729

51 Self Check 3.How do you construct an array of 10 strings? An array list of strings? Ans: new String[10]; new ArrayList ();

52 Self Check Continued… 4.What is the content of names after the following statements? Ans: names contains the strings " B " and " C " at positions 0 and 1 ArrayList names = new ArrayList (); names.add("A"); names.add(0, "B"); names.add("C"); names.remove(1);

53 Wrappers You cannot insert primitive types directly into array lists To treat primitive type values as objects, you must use wrapper classes: Continued… ArrayList data = new ArrayList (); data.add(29.95); double x = data.get(0);

54 Wrappers Figure 5: An Object of a Wrapper Class

55 Wrappers There are wrapper classes for all eight primitive types

56 Auto-boxing Auto-boxing: Starting with Java 5.0, conversion between primitive types and the corresponding wrapper classes is automatic. Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95); double x = d; // auto-unboxing; same as double x = d.doubleValue(); Continued…

57 Auto-boxing Auto-boxing even works inside arithmetic expressions Means: – auto-unbox d into a double – add 1 – auto-box the result into a new Double – store a reference to the newly created wrapper object in e Double e = d + 1;

58 Self Check 5.What is the difference between the types double and Double ? Ans: double is one of the eight primitive types. Double is a class type. 6.Suppose data is an ArrayList of size > 0. How do you increment the element with index 0? Ans: data.set(0, data.get(0) + 1);

59 The Enhanced for Loop Traverses all elements of a collection: Continued… double[] data =...; double sum = 0; for (double e : data) // You should read this loop as // "for each e in data" { sum += e; }

60 The Enhanced for Loop Traditional alternative: double[] data =...; double sum = 0; for (int i = 0; i < data.length; i++) { double e = data[i]; sum += e; }

61 The Enhanced for Loop Works for ArrayLists too: ArrayList accounts =... ; double sum = 0; for (BankAccount a : accounts) { sum += a.getBalance(); }

62 The Enhanced for Loop Equivalent to the following ordinary for loop: double sum = 0; for (int i = 0; i < accounts.size(); i++) { BankAccount a = accounts.get(i); sum = sum + a.getBalance(); }

63 Syntax 7.3: The "for each" Loop for (Type variable : collection) statement Example: for (double e : data) sum = sum + e; Purpose: To execute a loop for each element in the collection. In each iteration, the variable is assigned the next element of the collection. Then the statement is executed.

64 Self Check 7.Write a "for each" loop that prints all elements in the array data Ans: 8.Why is the "for each" loop not an appropriate shortcut for the following ordinary for loop? Ans: The loop writes a value into data[i]. The "for each" loop does not have the index variable i. for (int i = 0; i < data.length; i++) data[i] = i * i; for (double x : data) System.out.println(x);

65 Simple Array Algorithms: Counting Matches Check all elements and count the matches until you reach the end of the array list. public class Bank { public int count(double atLeast) { int matches = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) matches++; // Found a match } return matches; }... private ArrayList accounts; } Textbook Page

66 Simple Array Algorithms: Finding a Value Check all elements until you have found a match. public class Bank { public BankAccount find(int accountNumber) { for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) // Found a match return a; } return null; // No match in the entire array list }... }

67 Simple Array Algorithms: Finding the Maximum or Minimum Works only if there is at least one element in the array list If list is empty, return null if (accounts.size() == 0) return null; BankAccount largestYet = accounts.get(0);...

68 Initialize a candidate with the starting element Compare candidate with remaining elements Update it if you find a larger or smaller value Example: BankAccount largestYet = accounts.get(0); for (int i = 1; i < accounts.size(); i++) { BankAccount a = accounts.get(i); if (a.getBalance()> largestYet.getBalance()) largestYet = a; } return largestYet;

69 Two-Dimensional Arrays When constructing a two-dimensional array, you specify how many rows and columns you need: You access elements with an index pair a[i][j] final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; board[i][j] = "x";

70 Traversing Two-Dimensional Arrays It is common to use two nested loops when filling or searching: See File: TicTacToe.java – text pages for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

71 A Tic-Tac-Toe Board Figure 6: A Tic-Tac-Toe Board

72 Self Check 11.How do you declare and initialize a 4-by-4 array of integers? ans: int[][] array = new int[4][4]

73 Save test cases Use saved test cases in subsequent versions A test suite is a set of tests for repeated testing Cycling = bug that is fixed but reappears in later versions Regression testing: repeating previous tests to ensure that known failures of prior versions do not appear in new versions See regression/BankTester.java pp. 319 – 320. Regression Testing

74 Suppose you modified the code for a method. Why do you want to repeat tests that already passed with the previous version of the code? Answer: It is possible to introduce errors when modifying code. Self Check 7.15

75 Suppose a customer of your program finds an error. What action should you take beyond fixing the error? Answer: Add a test case to the test suite that verifies that the error is fixed. Self Check 7.16

76 Arrays/ Array lists Applications?

77 What to do with arrays…. Input – Get “stuff” into our array Process – Do something with the stuff in our array Output – Display contents of our array How? What? Where?

78 Input // filling arrays with consecutive integers for (count = 0;count < 20;count++) { v[count] = count ; } // filling array list with consecutive integers for (count = 0;count < 20;count++) { v.add(new Integer(count)); }

79 Input // filling array from file int count = 0; String pathname = "..h:\\yourFilename\\Data.txt“; File file = File(pathname); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException ex) { System.out.println("*** Cannot open " + pathname + " ***"); System.exit(1); // quit the program } try-catch block – page 508 of textbook

80 while(count < maxCount && input.hasNextInt()) { int a = input.nextInt(); arr[count] = a; count++; } size = count; //number of filled elements

81 Input // filling array list from file ArrayList arr = new ArrayList (); while(input.hasNextInt()) { int a = input.nextInt(); if (input.hasNextInt()) { arr.add(a); }

82 What about filling our 20-element container with random integers from 1 to 100? final int MAXELTS = 20; Random generator = new Random(); int[] a = new int[MAXELTS]; for(int k = 0; k < MAXELTS; k++) { a[k] = generator.nextInt(100) + 1; }

83 What about filling our 20-element container with random integers from 1 to 100? final int MAXELTS = 20; Random generator = new Random(); int[] a = new int[MAXELTS]; for(int k = 0; k < MAXELTS; k++) { a[k] = generator.nextInt(100) + 1; } How does this change with an ArrayList ?

84 final int MAXELTS = 20; Random generator = new Random(); ArrayList a = new ArrayList ; for (int k = 0; k < MAXELTS; k++) { int num = generator.nextInt(100)+1; a.add(num); } What about filling our 20-element container with random integers from 1 to ArrayList?

85 PROBLEM : Fill a 20-element 'container' with random integers from inclusive ensuring that there are no duplicate values in array.

86 We will look at several possible solutions. You will be asked for others. You will be asked your preference and a justification! Note : solutions are not given in Java code!

87 Solution 1 : for (int k = 0; k < 20; k++) – do Generate random integer(1-100) Check all elements in array that are filled already until random number is not a dupe – while (random num is a dupe); – Put the non-dupe in array * 8

88 Solution 1 : for (int k = 0; k < 20; k++) – do Generate random integer(1-100) Check all elements in array that are filled already until random number is not a dupe – while (random num is a dupe); – Put the non-dupe in array – space efficiency? – time efficiency? * 8

89 Solution 1 : for (int k = 0; k < 20; k++) – do Generate random integer(1-100) Check all elements in array that are filled already until random number is not a dupe – while (random num is a dupe); – Put the non-dupe in array – space efficiency? OK – time efficiency? not very * 8

90 Solution 2: Create an additional array, b, with 101 elements (random choices are from 1-100) and fill it with 0s. for (int k = 0; k < 20; k++) – do Choose a random number, r – while b[r] = 0 – Put r in your array – Put 1 in b[r] to mark it “taken”

91 Solution 2 : a picture for (int k=0; k < 20; k++) – do Choose a random number, r 8 – while b[r] = 0 – Put r in your array – Put 1 in b[r] to mark it “taken” 4 8 b[0] 0 b[1] 0 b[2] 0 b[3] 0 b[4] 1 b[5] 0 b[6] 0 b[7] 0 b[8] 1 b[9] 0 b[10] 0 b[11] 0 ab

92 Solution 3: Create an additional array, b, with 101 elements (random choices are from 1-100) and fill it with indices of b ( b[1] = 1, b[5]= 5). Set n = 100; for (int k=0;k<20;k++) – Choose a random number, r, in the range [1, n ] – Put r in your array – b[n] replaces b[r] – Decrement n

93 Solution 3 : a picture n= 100 for (int k=0; k < 20; k++) Choose a random number, r, in the range [1, n] 4 Put b[r] in your array b[n] replaces b[r] Decrement n n = 99 4 b[0] 0 b[1] 1 b[2] 2 b[3] 3 b[4] b[5] 5 b[6] 6 b[7] 7 b[8] 8 b[9] 9 b[10] 10 b[11] 11 A

94 Solution 4: Create an array, b, with 100 elements (random choices are from 1-100) and fill it with (index + 1) ( b[0] = 1, b[4]= 5 ). for (int k=0;k< 20;k++) – Choose a random number, r, in the range [0, 99] – Swap b[k] with b[r]

95 Solution 4 : a picture for (int k=0; k < 20; k++) – Choose a random number, r, in the range [0, 99] 4 – Swap b[r] with b[k] copy the first 20 elements of b to an array of size 20 and assign b to this reference. to swap: int temp = a[i]; a[i] = a[j]; a[j] = temp; b[0] 1 b[1] 2 b[2] 3 b[3] 4 b[4] 5 b[5] 6 b[6] 7 b[7] 8 b[8] 9 b[9] 10 b[10] 11 b[11]

96 Solution 5 : Assign to each of the first 100 elements of an ArrayList, b, the value of index + 1. Create a new empty ArrayList (or 20-element array), a. for(int x = 1; x < = 20; x++) – Choose a random integer in the range [0, b.size()] – Remove this element from b and add it to a.

97 Solution 5 : A picture Assign to each of the first 100 elements of an ArrayList, b, the value of index + 1. Create a new empty ArrayList, a. for(int x = 1; x < = 20; x++) – Choose a random integer in the range [0, b.size()] – Remove this element from b and add it to a

98 Other solutions ???

99 You should be able to Give advantages and disadvantages of each solution Discuss time and space considerations Commit to and defend one of the solutions

100 Now………. Our array is filled – (by some obscure method) Let’s process……. – Find the sum. – Find the mean. – Find the largest/smallest value. – Many other things we can do….

101 array Find the largest value in the array/array list int large = a[0]; for(int k = 0; k < a.length; k++) { if (a[k] > large) large = a[k]; } System.out.println("The largest value is: " + large);

102 array list Find the largest value in the array/array list ArrayList nums = new ArrayList (); int large = nums.get(0); for (int i = 0; i < nums.size(); i++) { int tempLarge = nums.get(i); if(tempLarge.compareTo(large) > 0) { large = tempLarge; } compareTo returns a value < 0 if tempLarge is less than large returns a value = 0 if tempLarge is equal to large returns a value > 0 if tempLarge is greater than large

103 PROBLEM/Example code: Report the number that has the longest sequence of consecutive repeated values in an array/array list. If the array contains , the number 3 should be reported) public static int longSequence(int[] v) { int seqIndex = 0; // holds index of number in seq int longSeq= 1; // holds longest sequence so far int count = 1; // current sequence length

104 for ( int k = 1; k < v.length; k++ ) { if ( v[k] == v[k-1] ) { count++; //current seq length if ( count > longSeq ) { longSeq = count; seqIndex = k; } else count = 1; } return v[seqIndex]; // ANSWER k = 1; int seqIndex = 0; int longSeq = 1; int count = 1

105 How else can we process ??? Find the largest number in array Determine if there are duplicates Find the mean (how?) Find the median (how?) Find the mode (how?) Sort the array (more on this later)

106 Declaring multiple arrays int[] a, b; // Declares two arrays – uninitialized now a = new int[10]; b = new int [10]; =============================== int a[], b; // Declares one array and one int int a, b[]; // Declares one array and one int

107 Initializer Lists int[] arr = {10, 20, 30, 40, 50, 60, 70, 80}; // Initializer list System.out.println("Printing arr"); for (int i = 0; i < arr.length; i++) // arr's length is 8 { System.out.print(arr[i] + " "); } //

108 A word about efficiency Problem: – Insert an element into an array (that is not full). Insert it as the first element. Insert it as the last element. Insert it in the middle. – Delete an element from an array. Delete the first element. Delete the last element. Delete a middle element.

109 A word about efficiency (using “big-Oh” notation) Problem: – Insert an element into an array (that is not full). Insert it as the first element. O(n) Insert it as the last element. O(1) Insert it in the middle. O(n) – Delete an element from an array. Delete the first element. O(n) Delete the last element. O(1) Delete a middle element. O(n)

110 A word about efficiency Problem: – Insert it as the first element. O(n)

111 A word about efficiency Problem: – Insert it as the first element. O(n) Will this work? for (int i = 1; i < arrayName.length; i++) arrayName[i] = arrayName[i - 1]; arrayName[0] = newValue; newValue = 90; __ __ __

112 A word about efficiency Problem: – Insert it as the first element. O(n) Will this work? for (int i = 1; i < arrayName.length; i++) arrayName[i] = arrayName[i - 1]; WRONG arrayName[0] = newValue; newValue = 90; __ __ __

113 A word about efficiency Problem: – Insert it as the first element. O(n) Will this work? for (int i = arrayName.length ; i > 0; i--) arrayName[i] = arrayName[i - 1]; arrayName[0] = newValue; newValue = 90; __ __ __

114 A word about efficiency Problem: – Insert it as the first element. O(n) Will this work? for (int i = arrayName.length - 1; i > 0; i--) arrayName[i] = arrayName[i - 1]; CORRECT arrayName[0] = newValue; newValue = 90; __ __ __

115 A word about efficiency Problem: – What about deleting an element? Algorithm? What about number of elements in the array? __ __ __

116 equals Using equals with array lists will use the default Object equals and will compare references not contents --. equals returns true if two ArrayList references are the same, false otherwise. When you use equals with arrays, you are also comparing references. array1.equals(array2) is asking if array1 and array2 reference the same array.

117 Arrays and Array Lists as Parameters to Methods: A method cannot change the size of an array parameter. Why not? A method can change the length of an array list that is passed as a parameter. Why? You can change the contents of the array/array list but you cannot change the reference.

118 Make Parallel Arrays into Arrays of Objects Figure 13: Avoid Parallel Arrays // Don't do this int[] accountNumbers; double[] balances;

119 Make Parallel Arrays into Arrays of Objects Avoid parallel arrays by changing them into arrays of objects: Figure 14: Reorganizing Parallel Arrays into Arrays of Objects BankAccount[] = accounts;

120 java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileWriter FilterInputStream FilterOutputStream FilterReader FilterWriter InputStream InputStreamReader LineNumberInputStream LineNumberReader ObjectInputStream ObjectInputStream.GetField ObjectOutputStream ObjectOutputStream.PutField ObjectStreamClass ObjectStreamField OutputStream OutputStreamWriter PipedInputStream PipedOutputStream PipedReader PipedWriter PrintStream PrintWriter PushbackInputStream PushbackReader RandomAccessFile Reader SequenceInputStream SerializablePermission StreamTokenizer StringBufferInputStream StringReader StringWriter Writer How do I read an int from a file?

121 java.io (cont’d) Uses four hierarchies of classes rooted at Reader, Writer, InputStream, OutputStream. InputStream/OutputStream hierarchies deal with bytes. Reader/Writer hierarchies deal with chars. Has a special stand-alone class RandomAccessFile. The Scanner class has been added to java.util in Java 5 to facilitate reading numbers and words.

122 java.io.File The File class represents a file (or folder) in the file directory system. Methods: String getName() // Returns the name of the file or directory String getAbsolutePath() // Returns the absolute pathname string long length() // Returns the length of the file boolean isDirectory() //tests if file is a directory File[ ] listFiles() // Returns an array of abstract pathnames denoting //the files in the directory String pathname = "../Data/words.txt“; File file = new File(pathname);

123 Reading from a Text File String pathname = "words.txt"; File file = new File(pathname); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException ex) { System.out.println("*** Cannot open " + pathname + " ***"); System.exit(1); // quit the program } Tries to open the file

124 Scanner Methods boolean hasNextLine() String nextLine() boolean hasNext() String next() boolean hasNextInt() int nextInt() boolean hasNextDouble() double nextDouble() void close() Reads one word

125 Writing to a Text File String pathname = "output.txt"; File file = new File(pathname); PrintWriter output = null; try { output = new PrintWriter(file); } catch (FileNotFoundException ex) { System.out.println("Cannot create " + pathname); System.exit(1); // quit the program } output.println(...); output.printf(...); output.close(); Required to flush the output buffer

126 Summary We can create arrays/ array lists We can fill them We can process them We can output their contents Which do we use….. – Array lists? – Arrays?

127 Programming Exercises Continued… Fun Number Lab2 – FunNumber2.java on s:\drive – Read in FNUM1, FNUM2, and FNUM3 lists from the s:\ drive in Assignments/AP Java/data(See chapter 11.1 for file reading using Scanner class) Find: – Number of elements – Maximum – Minimum – Mode – Median – Mean


Download ppt "Chapter 7 Arrays and Array Lists. Assignment: Read lessons 7.1 thru 7.8, take notes, and complete the self- check questions in your notebook Written exercises:"

Similar presentations


Ads by Google