Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 7 Arrays and Array Lists Assignment: • Read lessons 7.1 thru 7.8, take notes, and complete the selfcheck questions in your notebook • Written exercises: R7.1, 7.3, 7.4,7.6 – 7.7 R7.11, 7.12, 7.16 – 7.19 -- Due December 9, 2013 • Programming exercises P7.2 – 7.6, 7.9, 7.10, 7.13 -- 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 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… 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 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. Arrays • Construct array: double[] data = new double[10]; • Store in variable of type double[ ] new double[10] • Find Length of an array System.out.println (data.length); Continued… Arrays • Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array. 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: 78 89 0 0 0 Arrays • When array is created, all values are initialized depending on array type: – Numbers: 0 – Boolean: false – Object References: null Arrays Figure 1: An Array Reference and an Array Arrays • Use [ ] to access an element data[2] = 29.95; Figure 2: Storing a Value in an Array Arrays • Using the value stored: System.out.println("The value of this data item is " + data[4]); • Get array length as data.length. (Not a method!) • Index values range from 0 to(length - 1) Array Name Continued… 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 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(); } Arrays • Accessing a nonexistent element results in a bounds error double[] data = new double[10]; data[10] = 29.95; // ERROR • Limitation: Arrays have fixed length Self Check 1. What elements does the data array contain after the following statements? double[] data = new double[10]; for (int i = 0; i < data.length; i++) data[i] = i * i; Ans: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not 100 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. 1. 2. 3. double[] a = new double[10]; System.out.println(a[0]); double[] b = new double[10]; System.out.println(b[10]); double[] c; System.out.println(c[0]); 1. 0 2. a runtime error: array index out of bounds 3. a compile-time error: c is not initialized 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… Copying Arrays: Copying Array References Figure 7: Two References to the Same Array Copying Arrays: Cloning Arrays • Use clone to make true copy double[] prices = (double[]) data.clone(); Need to cast as a (double) since cloned type is an Object Continued… Copying Arrays: Cloning Arrays Figure 8: Cloning an Array Copying Arrays: Copying Array Elements System.arraycopy(from, fromStart, to, toStart, count); From Array Name To Array Name How many elements to copy Continued… Copying Arrays: Copying Array Elements Figure 9: The System.arraycopy Method 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. Growing an Array • If the array is full and you need more space, you can grow the array: 1. Create a new, larger array. double[] newData = new double[2 * data.length]; 2. Copy all elements into the new array System.arraycopy(data, 0, newData, 0, data.length); 3. Store the reference to the new array in the array variable data = newData; Arrays • You must allocate a larger array and copy the elements from the original array to the larger array. By setting data = newData the array data now references the copy. data free space newData Growing an Array Figure 12: Growing an Array 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; 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… Simple Array Algorithms: Finding the Maximum or Minimum • Example: BankAccount largestYet = accounts[0]; for (int i = 1; i < accounts.length; i++) { BankAccount a = accounts[i]; if (a.getBalance() > largestYet.getBalance()) largestYet = a; } return largestYet; 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}; 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? 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! "Too Many Daves" 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. http://www.mit.edu/people/dpolicar/writing/poetry/poems/tooManyDaves.html 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! 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. 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. 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. 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. 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. 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. Array Lists • The ArrayList class is a generic class: ArrayList<T> collects objects of type T: ArrayList<BankAccount> accounts = new ArrayList<BankAccount>(); accounts.add(new BankAccount(1001)); accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1022)); • size method yields number of elements Retrieving Array List Elements • Use get method • Index starts at 0 • BankAccount anAccount = accounts.get(2); // gets the third element of the array list • Bounds error if index is out of range Continued… 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 Adding Elements • set overwrites an existing value BankAccount anAccount = new BankAccount(1729); accounts.set(2, anAccount); • add adds a new value before the index accounts.add(i, a) Continued… Adding Elements Figure 3: Adding an Element in the Middle of an Array List Removing Elements • remove removes an element at an index Accounts.remove(i) Continued… Removing Elements Figure 4: Removing an Element in the Middle of an Array List File: ArrayListTester.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: - p294-296 import java.util.ArrayList; /** This program tests the ArrayList class. */ public class ArrayListTester { public static void main(String[] args) { ArrayList<BankAccount> accounts = new ArrayList<BankAccount>(); accounts.add(new BankAccount(1001)); accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1729)); accounts.add(1, new BankAccount(1008)); accounts.remove(0); Continued… 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 Self Check 3. How do you construct an array of 10 strings? An array list of strings? Ans: new String[10]; new ArrayList<String>(); Self Check Continued… 4. What is the content of names after the following statements? ArrayList<String> names = new ArrayList<String>(); names.add("A"); names.add(0, "B"); names.add("C"); names.remove(1); Ans: names contains the strings "B" and "C" at positions 0 and 1 Wrappers • You cannot insert primitive types directly into array lists • To treat primitive type values as objects, you must use wrapper classes: ArrayList<Double> data = new ArrayList<Double>(); data.add(29.95); double x = data.get(0); Continued… Wrappers Figure 5: An Object of a Wrapper Class Wrappers • There are wrapper classes for all eight primitive types 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… Auto-boxing • Auto-boxing even works inside arithmetic expressions Double e = d + 1; 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 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<Double> of size > 0. How do you increment the element with index 0? Ans: data.set(0, data.get(0) + 1); The Enhanced for Loop • Traverses all elements of a collection: double[] data = . . .; double sum = 0; for (double e : data) // You should read this loop as // "for each e in data" { sum += e; } Continued… 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; } The Enhanced for Loop • Works for ArrayLists too: ArrayList<BankAccount> accounts = . . . ; double sum = 0; for (BankAccount a : accounts) { sum += a.getBalance(); } 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(); } 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. Self Check 7. Write a "for each" loop that prints all elements in the array data Ans: for (double x : data) System.out.println(x); 8. Why is the "for each" loop not an appropriate shortcut for the following ordinary for loop? for (int i = 0; i < data.length; i++) data[i] = i * i; Ans: The loop writes a value into data[i]. The "for each" loop does not have the index variable i. Textbook Page 303-305 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<BankAccount> accounts; } 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 } . . . } 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); . . . • • • • 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; Two-Dimensional Arrays • When constructing a two-dimensional array, you specify how many rows and columns you need: final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; • You access elements with an index pair a[i][j] board[i][j] = "x"; Traversing Two-Dimensional Arrays • It is common to use two nested loops when filling or searching: for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " "; • See File: TicTacToe.java – text pages 307-308 A Tic-Tac-Toe Board Figure 6: A Tic-Tac-Toe Board Self Check 11.How do you declare and initialize a 4-by-4 array of integers? ans: int[][] array = new int[4][4] Regression Testing • 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. Self Check 7.15 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.16 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. Arrays/ Array lists Applications? What to do with arrays…. • Input – Get “stuff” into our array How? • Process – Do something with the stuff in our array What? • Output – Display contents of our array Where? 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)); } 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 while(count < maxCount && input.hasNextInt()) { int a = input.nextInt(); arr[count] = a; count++; } size = count; //number of filled elements Input // filling array list from file ArrayList<Integer> arr = new ArrayList<Integer>(); while(input.hasNextInt()) { int a = input.nextInt(); if (input.hasNextInt()) { arr.add(a); } } 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; } 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? What about filling our 20-element container with random integers from 1 to 100 -- ArrayList? final int MAXELTS = 20; Random generator = new Random(); ArrayList<Integer> a = new ArrayList<Integer>; for (int k = 0; k < MAXELTS; k++) { int num = generator.nextInt(100)+1; a.add(num); } PROBLEM : Fill a 20-element 'container' with random integers from 1100 inclusive ensuring that there are no duplicate values in array. PROBLEM : Fill a 20-element 'container' with random integers from 1100 inclusive ensuring that there are no duplicate values in array. • 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! Solution 1 : 4 • for (int k = 0; k < 20; k++) 6 – do 8 23 8 * • 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 Solution 1 : 4 8 • for (int k = 0; k < 20; k++) – do 8 • 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? 6 23 * Solution 1 : 4 8 • for (int k = 0; k < 20; k++) – do 8 • 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 6 23 * 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” 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” b a b[0] 0 4 b[1] 0 0 8 b[2] b[3] b[4] b[5] b[6] b[7] b[8] b[9] b[10] b[11] 0 1 0 0 0 1 0 0 0 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 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 A b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7] b[8] b[9] b[10] b[11] 0 1 2 3 4100 5 6 7 8 9 10 11 4 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] 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] b[0] b[1] b[2] b[3] b[4] b[5] b[6] • 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[7] b[8] b[9] b[10] b[11] 1 5 2 3 4 5 1 6 7 8 9 10 11 12 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. 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. 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 9 10 1 8 3 2 4 5 6 7 9 10 Other solutions ??? • • • • • • 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 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…. 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); Find the largest value in the array/array list ArrayList<Integer>nums = new ArrayList<Integer>(); 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 PROBLEM/Example code: Report the number that has the longest sequence of consecutive repeated values in an array/array list. If the array contains 3 5 6 8 3 0 0 4 4 4 2 3 3 3 3 3 9 9 9, 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 3 5 6 8 3 0 0 4 4 4 2 33 3 3 3 9 9 9 for ( int k = 1; k < v.length; k++ ) { if ( v[k] == v[k-1] ) { count++; //current seq length if ( count > longSeq ) k = 1; { longSeq = count; int seqIndex = 0; seqIndex = k; } int longSeq = 1; } else count = 1; } return v[seqIndex]; // ANSWER int count = 1 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) 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 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] + " "); } // 10 20 30 40 50 60 70 80 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. 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) A word about efficiency • Problem: – Insert it as the first element. O(n) 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; 12 13 14 88 45 32 17 __ __ __ 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; 12 13 14 88 45 32 17 __ __ __ 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; 12 13 14 88 45 32 17 __ __ __ 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; 12 13 14 88 45 32 17 __ __ __ A word about efficiency • Problem: – What about deleting an element? Algorithm? What about number of elements in the array? 12 13 14 88 45 32 17 __ __ __ 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. 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. Make Parallel Arrays into Arrays of Objects • // Don't do this int[] accountNumbers; double[] balances; Figure 13: Avoid Parallel Arrays Make Parallel Arrays into Arrays of Objects • Avoid parallel arrays by changing them into arrays of objects: BankAccount[] = accounts; Figure 14: Reorganizing Parallel Arrays into Arrays of Objects 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? 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. java.io.File • The File class represents a file (or folder) in the file directory system. String pathname = "../Data/words.txt“; File file = new File(pathname); • 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 Reading from a Text File String pathname = "words.txt"; Tries to open File file = new File(pathname); the file Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException ex) { System.out.println("*** Cannot open " + pathname + " ***"); System.exit(1); // quit the program } Scanner Methods boolean hasNextLine() String nextLine() boolean hasNext() String next() boolean hasNextInt() int nextInt() boolean hasNextDouble() double nextDouble() void close() Reads one word 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(...); Required to flush output.close(); the output buffer 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? 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