Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists.

Slides:



Advertisements
Similar presentations
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Advertisements

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7: Arrays and Array Lists. To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists.
Chapter 13 ARRAY LISTS AND ARRAYS. CHAPTER GOALS To become familiar with using array lists to collect objects To learn about common array algorithms To.
Chapter 7 Arrays and Array Lists. Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the.
Chapter 13 ARRAY LISTS AND ARRAYS CHAPTER GOALS –To become familiar with using array lists to collect objects –To learn about common array algorithms –To.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Our BankAccount class should define three methods  deposit  withdraw  getBalance How a programmer will carry out these operations?  We assume that.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Arrays.
Chapter 7 – Arrays.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Java Programming Week 6: Array and ArrayList Chapter 7.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Week 9-10 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists.
ICOM 4015: Advanced Programming Lecture 7 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Seven:
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ARRAYLIST Collections of Data. ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 6 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays. Array: Sequence of values of the same type Construct array: Store in variable of type double[ ] new double[10] double[] data = new double[10];
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] : double[] data = new double[10]; When array.
Chapter 3 Implementing Classes
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
A 2-D Array is a structure that storage space both vertically and horizontally. Thus, the array has both rows and columns. 2-D Arrays are used to create.
Chapter 7 – Arrays and Array Lists
Lecture 3 John Woodward.
Principles of Computer Science I
Chapter 7 – Arrays and Array Lists
Chapter 8 – Arrays and Array Lists
7.6 Common Array Algorithm: Filling
Lecture Notes – Arrays and ArrayLists (Ch 7-8)
Introduction to Computer Science and Object-Oriented Programming
Chapter Three - Implementing Classes
Chapter 8 Arrays and Array Lists
Object Oriented Programming in java
Presentation transcript:

Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists

Chapter 7  Arrays and Array Lists 2 Chapter Goals  To become familiar with using arrays and array lists  To learn about wrapper classes, auto-boxing and the generalized for loop ( for each loop)  To study common array algorithms  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

Chapter 7  Arrays and Array Lists 3 Arrays  Array is sequence of values of the same type  Construct array:  Store in variable of appropriate type  Note the use of double[]  The “ [] ” tells compiler it is an array new double[10] double[] data = new double[10];

Chapter 7  Arrays and Array Lists 4 Arrays  When array is created, all values are initialized depending on array type…  Numbers: 0  Boolean: false  Object References: null  If unsure of default initialization, you could…  Look up the answer in the Java API, or  Initialize everything yourself

Chapter 7  Arrays and Array Lists 5 Arrays Figure 1: An Array Reference and an Array

Chapter 7  Arrays and Array Lists 6 Arrays  Use [ ] to access an element Figure 2: Storing a Value in an Array data[2] = 29.95;  Note that indexing starts from 0

Chapter 7  Arrays and Array Lists 7 Arrays  Example: using the value stored in an array…  Get array “length” as data.length  Note that there are no parentheses  So, length is not a method (then what is it???)  Range of array index values  From 0 to length - 1 System.out.println("The value of this data item is " + data[4]);

Chapter 7  Arrays and Array Lists 8 Arrays  Accessing a nonexistent element results in a bounds error  The major limitation or arrays is…  Once specified, array has a fixed length  Why is this a problem?  Array cannot grow or shrink if need arises double[] data = new double[10]; data[10] = 29.95; // ERROR

Chapter 7  Arrays and Array Lists 9 Syntax 8.1: Array Construction new typeName[length] Example: new double[10] Purpose: To construct an array with a given number of elements

Chapter 7  Arrays and Array Lists 10 Syntax 8.2: Array Element Access arrayReference[index] Example: data[2] Purpose: To access an element in an array

Chapter 7  Arrays and Array Lists 11 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; }

Chapter 7  Arrays and Array Lists 12 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) double[] a = new double[10]; System.out.println(a[0]); b) double[] b = new double[10]; System.out.println(b[10]); c) double[] c; System.out.println(c[0]);

Chapter 7  Arrays and Array Lists 13 Answers 1. 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not a)0 b)a run-time error: array index out of bounds c)a compile-time error: c is not initialized

Chapter 7  Arrays and Array Lists 14 Bounds Errors  Errors with array bounds are common  For example, will generate a run-time error  For programmers, this is an improvement over C/C++  In C and C++ no error is given  Makes programs harder to debug  C/C++ programs can do strange things as a result double[] data = new double[10]; data[10] = 29.95; // ERROR --- no data[10]

Chapter 7  Arrays and Array Lists 15 Uninitialized Arrays  Another common error is to allocate array reference, but not the actual array  Must use new to generate an array double[] data; data[10] = 29.95; // ERROR --- data not initialized double[] data = new double[11]; data[10] = 29.95; // this will work

Chapter 7  Arrays and Array Lists 16 Array Initialization  A common way to initialize an array:  And a sometimes useful shortcut:  Also possible to create “anonymous” array  Can pass anonymous array to a method int[] primes = new int[3]; primes[0] = 2; primes[1] = 3; primes[2] = 5; int[] primes = {2, 3, 5}; new int[] {2, 3, 5}

Chapter 7  Arrays and Array Lists 17 Array Lists  The ArrayList class manages a sequence of objects  An ArrayList can grow and shrink as needed  An array does not automatically grow or shrink  ArrayList class has many useful methods:  add method appends an element to ArrayList  remove method removes element from ArrayList  size method returns number of elements in ArrayList  get method gets specified element  set method sets specified element to a value

Chapter 7  Arrays and Array Lists 18 Array Lists  Consider BankAccount class  Suppose have account number and balance  Constructor requires an account number  An ArrayList of three BankAccount s: ArrayList accounts = new ArrayList (); accounts.add(new BankAccount(1001)); // account number 1001 accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1022));

Chapter 7  Arrays and Array Lists 19 Retrieving ArrayList Elements  Use get method to get ArrayList element  Note that indexing starts at 0  Bounds error if index is out of range BankAccount anAccount = accounts.get(2); // gets the third element of the array list

Chapter 7  Arrays and Array Lists 20 Retrieving Array List Elements  Most common bounds error int i = accounts.size(); anAccount = accounts.get(i); // Error // legal index values are 0,1,...,i-1

Chapter 7  Arrays and Array Lists 21 Adding Elements  set can only overwrite an existing value  add can also insert an object at an index  Following objects moved “up” by one BankAccount anAccount = new BankAccount(1729); accounts.set(2, anAccount); accounts.add(i, a);

Chapter 7  Arrays and Array Lists 22 Adding Elements Figure 3: Adding an Element in the Middle of an Array List b c d e f g b c d e f g

Chapter 7  Arrays and Array Lists 23 Removing Elements  remove removes an element at an index  Following objects moved “down” by one accounts.remove(i);

Chapter 7  Arrays and Array Lists 24 Removing Elements Figure 4: Removing an Element in the Middle of an ArrayList b c d e f c d e f i

Chapter 7  Arrays and Array Lists 25 File: ArrayListTester.java 01: 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…

Chapter 7  Arrays and Array Lists 26 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: }

Chapter 7  Arrays and Array Lists 27 File: BankAccount.java 01: /** 02: A bank account has a balance that can be changed by 03: deposits and withdrawals. 04: */ 05: public class BankAccount 06: { 07: /** 08: Constructs a bank account with a zero balance anAccountNumber account number for account 10: */ 11: public BankAccount(int anAccountNumber) 12: { 13: accountNumber = anAccountNumber; 14: balance = 0; 15: } 16: Continued…

Chapter 7  Arrays and Array Lists 28 File: BankAccount.java 17: /** 18: Constructs a bank account with a given balance anAccountNumber the account number for this account initialBalance the initial balance 21: */ 22: public BankAccount(int anAccountNumber, double initialBalance) 23: { 24: accountNumber = anAccountNumber; 25: balance = initialBalance; 26: } 27: 28: /** 29: Gets the account number of this bank account. the account number 31: */ 32: public int getAccountNumber() 33: { 34: return accountNumber; 35: } Continued…

Chapter 7  Arrays and Array Lists 29 File: BankAccount.java 36: 37: /** 38: Deposits money into the bank account. amount the amount to deposit 40: */ 41: public void deposit(double amount) 42: { 43: double newBalance = balance + amount; 44: balance = newBalance; 45: } 46: 47: /** 48: Withdraws money from the bank account. amount the amount to withdraw 50: */ 51: public void withdraw(double amount) 52: { 53: double newBalance = balance - amount; 54: balance = newBalance; Continued…

Chapter 7  Arrays and Array Lists 30 File: BankAccount.java 55: } 56: 57: /** 58: Gets the current balance of the bank account. the current balance 60: */ 61: public double getBalance() 62: { 63: return balance; 64: } 65: 66: private int accountNumber; 67: private double balance; 68: }

Chapter 7  Arrays and Array Lists 31 File: ArrayListTester.java size=3 first account number=1008 last account number=1729 Output

Chapter 7  Arrays and Array Lists 32 Self Check 3. How do you construct an array of 10 strings? An array list of strings? 4. What is the content of names after the following statements? ArrayList names = new ArrayList (); names.add("A"); names.add(0, "B"); names.add("C"); names.remove(1);

Chapter 7  Arrays and Array Lists 33 Answers names contains the strings " B " and " C " at positions 0 and 1, respectively new String[10]; new ArrayList ();

Chapter 7  Arrays and Array Lists 34 Length and Size  Java syntax for size (length) of arrays, Array Lists, and Strings is not consistent Data typeNumber of elements Array a.length Array List a.size() String a.length()

Chapter 7  Arrays and Array Lists 35 Wrappers  You cannot insert primitive types directly into array lists (why?)  To treat primitive type values as objects, you must use wrapper classes  Note the capital “ D ” in Double ArrayList data = new ArrayList (); data.add(29.95); double x = data.get(0);

Chapter 7  Arrays and Array Lists 36 Wrappers Figure 5: An Object of a Wrapper Class

Chapter 7  Arrays and Array Lists 37 Wrappers  There are wrapper classes for all eight primitive types  Note Uppercase  Note also, 2 of the wrapper classes are spelled different than corresponding primitive type

Chapter 7  Arrays and Array Lists 38 Auto-boxing  Starting with Java 5.0, conversion between primitive types and the corresponding wrapper classes is automatic  Known as auto-boxing (not auto-wrapping) 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();

Chapter 7  Arrays and Array Lists 39 Auto-boxing  Auto-boxing works inside arithmetic expressions  What happens here, assuming d is a Double ?  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;

Chapter 7  Arrays and Array Lists 40 Self Check 5. What is the difference between the types double and Double ? 6. Suppose data is an ArrayList of size greater than 0. How do you increment the element with index 0?

Chapter 7  Arrays and Array Lists 41 Answers 5. The difference is that double is one of the primitive types while Double is a class type 6. data.set(0, data.get(0) + 1);

Chapter 7  Arrays and Array Lists 42 The for each Loop  for each or “generalized for loop”  Traverses all elements of a collection double[] data = new double[100];... double sum = 0; for (double e : data) // means "for each e in data" { sum = sum + e; }

Chapter 7  Arrays and Array Lists 43 The for each Loop  “Traditional” alternative to for each loop double[] data = new double[100];... double sum = 0; for (int i = 0; i < data.length; i++) { double e = data[i]; sum = sum + e; }

Chapter 7  Arrays and Array Lists 44 The for each Loop  Works for ArrayLists too… ArrayList accounts = new ArrayList ();... double sum = 0; for (BankAccount a : accounts) { sum = sum + a.getBalance(); }

Chapter 7  Arrays and Array Lists 45 The for each Loop  for each on previous slide is 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(); }

Chapter 7  Arrays and Array Lists 46 Syntax 8.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.

Chapter 7  Arrays and Array Lists 47 Self Check 7. Write a for each loop that prints all elements in the array data, where data is an array of doubles 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;

Chapter 7  Arrays and Array Lists 48 Answers The loop assigns a value to data[i] and the for each loop does not have the index variable i for (double x : data) System.out.println(x);

Chapter 7  Arrays and Array Lists 49 Array Algorithm: Counting Matches  Check all elements and count the matches until you reach the end of 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; }

Chapter 7  Arrays and Array Lists 50 Array Algorithm: Finding a Value  Check elements until you find a match public class Bank { public BankAccount find(int accountNumber) { for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) // Found match return a; } return null; // No match in the entire array list }... }

Chapter 7  Arrays and Array Lists 51 Array Algorithm: Find Max or Min  Initialize a candidate with the first element  Compare candidate with remaining elements  Update it if you find a larger (or smaller) value

Chapter 7  Arrays and Array Lists 52 Array Algorithm: Find Max or Min  For example, BankAccount largestYet = accounts.get(0); for (int i = 1; i largestYet.getBalance()) largestYet = a; } return largestYet;

Chapter 7  Arrays and Array Lists 53 Array Algorithm: Find Max or Min  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);...

Chapter 7  Arrays and Array Lists 54 File Bank.java 01: import java.util.ArrayList; 02: 03: /** 04: This bank contains a collection of bank accounts. 05: */ 06: public class Bank 07: { 08: /** 09: Constructs a bank with no bank accounts. 10: */ 11: public Bank() 12: { 13: accounts = new ArrayList (); 14: } 15: 16: /** 17: Adds an account to this bank. a the account to add 19: */ Continued…

Chapter 7  Arrays and Array Lists 55 File Bank.java 20: public void addAccount(BankAccount a) 21: { 22: accounts.add(a); 23: } 24: 25: /** 26: Gets the sum of the balances of all accounts in this bank. the sum of the balances 28: */ 29: public double getTotalBalance() 30: { 31: double total = 0; 32: for (BankAccount a : accounts) 33: { 34: total = total + a.getBalance(); 35: } 36: return total; 37: } 38: Continued…

Chapter 7  Arrays and Array Lists 56 File Bank.java 39: /** 40: Counts the number of bank accounts whose balance is at 41: least a given value. atLeast the balance required to count an account the no. of accounts with at least balance 44: */ 45: public int count(double atLeast) 46: { 47: int matches = 0; 48: for (BankAccount a : accounts) 49: { 50: if (a.getBalance() >= atLeast) matches++; // match 51: } 52: return matches; 53: } 54: Continued…

Chapter 7  Arrays and Array Lists 57 File Bank.java 55: /** 56: Finds a bank account with a given number. accountNumber the number to find the account with the given number, or null 59: if there is no such account 60: */ 61: public BankAccount find(int accountNumber) 62: { 63: for (BankAccount a : accounts) 64: { 65: if (a.getAccountNumber() == accountNumber) // Found a match 66: return a; 67: } 68: return null; // No match in the entire array list 69: } 70: Continued…

Chapter 7  Arrays and Array Lists 58 File Bank.java 71: /** 72: Gets the bank account with the largest balance. the account with the largest balance, or 74: null if the bank has no accounts 75: */ 76: public BankAccount getMaximum() 77: { 78: if (accounts.size() == 0) return null; 79: BankAccount largestYet = accounts.get(0); 80: for (int i = 1; i < accounts.size(); i++) 81: { 82: BankAccount a = accounts.get(i); 83: if (a.getBalance() > largestYet.getBalance()) 84: largestYet = a; 85: } 86: return largestYet; 87: } 88: 89: private ArrayList accounts; 90: }

Chapter 7  Arrays and Array Lists 59 File BankTester.java 01: /** 02: This program tests the Bank class. 03: */ 04: public class BankTester 05: { 06: public static void main(String[] args) 07: { 08: Bank firstBankOfJava = new Bank(); 09: firstBankOfJava.addAccount(new BankAccount(1001, 20000)); 10: firstBankOfJava.addAccount(new BankAccount(1015, 10000)); 11: firstBankOfJava.addAccount(new BankAccount(1729, 15000)); 12: 13: double threshold = 15000; 14: int c = firstBankOfJava.count(threshold); 15: System.out.println(c + " accounts with balance >= " + threshold); Continued…

Chapter 7  Arrays and Array Lists 60 File BankTester.java 16: 17: int accountNumber = 1015; 18: BankAccount a = firstBankOfJava.find(accountNumber); 19: if (a == null) 20: System.out.println("No account with number " + accountNumber); 21: else 22: System.out.println("Account with number " + accountNumber 23: + " has balance " + a.getBalance()); 24: 25: BankAccount max = firstBankOfJava.getMaximum(); 26: System.out.println("Account with number " 27: + max.getAccountNumber() 28: + " has the largest balance."); 29: } 30: } Continued…

Chapter 7  Arrays and Array Lists 61 File BankTester.java Output 2 accounts with balance >= Account with number 1015 has balance Account with number 1001 has the largest balance.

Chapter 7  Arrays and Array Lists 62 Self Check 9. What does the find method do if there are two bank accounts with a matching account number? 10. Would it be possible to use a for each loop in the getMaximum method?

Chapter 7  Arrays and Array Lists 63 Answers 9. It returns the first match that it finds 10. Yes, but the first comparison would always fail

Chapter 7  Arrays and Array Lists 64 Two-Dimensional Arrays  When constructing a 2-dimensional array, you specify how many rows and columns you need  You access elements with index pair, where i is row index, j is column index final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; board[i][j] = "x";

Chapter 7  Arrays and Array Lists 65 A Tic-Tac-Toe Board Figure 6: A Tic-Tac-Toe Board

Chapter 7  Arrays and Array Lists 66 Traversing Two-Dimensional Arrays  We 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] = " ";

Chapter 7  Arrays and Array Lists 67 File TicTacToe.java 01: /** 02: A 3 x 3 tic-tac-toe board. 03: */ 04: public class TicTacToe 05: { 06: /** 07: Constructs an empty board. 08: */ 09: public TicTacToe() 10: { 11: board = new String[ROWS][COLUMNS]; 12: // Fill with spaces 13: for (int i = 0; i < ROWS; i++) 14: for (int j = 0; j < COLUMNS; j++) 15: board[i][j] = " "; 16: } 17: Continued…

Chapter 7  Arrays and Array Lists 68 File TicTacToe.java 18: /** 19: Sets a field in the board. Field must be unoccupied. i the row index j the column index player the player ("x" or "o") 23: */ 24: public void set(int i, int j, String player) 25: { 26: if (board[i][j].equals(" ")) 27: board[i][j] = player; 28: } 29: 30: /** 31: Creates a string representation of the board, like 32: |x o| 33: | x | 34: | o| the string representation 36: */ Continued…

Chapter 7  Arrays and Array Lists 69 File TicTacToe.java 37: public String toString() 38: { 39: String r = ""; 40: for (int i = 0; i < ROWS; i++) 41: { 42: r = r + "|"; 43: for (int j = 0; j < COLUMNS; j++) 44: r = r + board[i][j]; 45: r = r + "|\n"; 46: } 47: return r; 48: } 49: 50: private String[][] board; 51: private static final int ROWS = 3; 52: private static final int COLUMNS = 3; 53: }

Chapter 7  Arrays and Array Lists 70 File TicTacToeTester.java 01: import java.util.Scanner; 02: 03: /** 04: This program tests the TicTacToe class by prompting the 05: user to set positions on the board and printing out the 06: result. 07: */ 08: public class TicTacToeTester 09: { 10: public static void main(String[] args) 11: { 12: Scanner in = new Scanner(System.in); 13: String player = "x"; 14: TicTacToe game = new TicTacToe(); 15: boolean done = false; 16: while (!done) 17: { Continued…

Chapter 7  Arrays and Array Lists 71 File TicTacToeTester.java 18: System.out.print(game.toString()); 19: System.out.print( 20: "Row for " + player + " (-1 to exit): "); 21: int row = in.nextInt(); 22: if (row < 0) done = true; 23: else 24: { 25: System.out.print("Column for " + player + ": "); 26: int column = in.nextInt(); 27: game.set(row, column, player); 28: if (player.equals("x")) 29: player = "o"; 30: else 31: player = "x"; 32: } 33: } 34: } 35: } Continued…

Chapter 7  Arrays and Array Lists 72 Output | | | | | | Row for x (-1 to exit): 1 Column for x: 2 | | x| | Row for o (-1 to exit): 0 Column for o: 0 |o | | x| | Row for x (-1 to exit): -1

Chapter 7  Arrays and Array Lists 73 Self Check 11. How do you declare and initialize a 4 by 4 array of integers? 12. How do you count the number of unused spaces in the tic-tac-toe board?

Chapter 7  Arrays and Array Lists 74 Answers int[][] array = new int[4][4]; int count = 0; for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) if (board[i][j].equals(" ")) count++;

Chapter 7  Arrays and Array Lists 75  Copying an array variable yields another reference to the same array double[] data = new double[10]; // fill array... double[] prices = data; Copying Arrays: Copying Array References

Chapter 7  Arrays and Array Lists 76 Copying Arrays: Copying Array References Figure 7: Two References to the Same Array

Chapter 7  Arrays and Array Lists 77 Copying Arrays: Cloning Arrays  Use clone to make a distinct copy of an array  The cast is necessary! double[] prices = (double[]) data.clone();

Chapter 7  Arrays and Array Lists 78 Copying Arrays: Cloning Arrays Figure 8: Cloning an Array

Chapter 7  Arrays and Array Lists 79 Copying Arrays: Copying Array Elements  Use arrayCopy in System class to copy elements of one array to another  Useful, for example, to copy element(s) to or from middle of an array System.arraycopy(from, fromStart, to, toStart, count);

Chapter 7  Arrays and Array Lists 80 Copying Arrays: Copying Array Elements Figure 9: System.arraycopy Method

Chapter 7  Arrays and Array Lists 81 Adding an Element to an Array  To insert element at position i, move all elements from i onward, up one position  To remove element at position i, move all elements above i down one position System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x; System.arraycopy(data, i + 1, data, i, data.length - i - 1);

Chapter 7  Arrays and Array Lists 82 Adding an Element to an Array Figure 10: Inserting a New Element Into an Array

Chapter 7  Arrays and Array Lists 83 Removing an Element from an Array Figure 11 Removing an Element from an Array

Chapter 7  Arrays and Array Lists 84 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 double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

Chapter 7  Arrays and Array Lists 85 Growing an Array Figure 12: Growing an Array

Chapter 7  Arrays and Array Lists 86 Self Check 13. How do you add or remove elements in the middle of an Array List? 14. Why do we double the length of the array when it has run out of space rather than increasing it by one element?

Chapter 7  Arrays and Array Lists 87 Answers 13. Use the add and remove methods. 14. Allocating a new array and copying the elements is time-consuming, so you do not want to go through the process every time you add an element

Chapter 7  Arrays and Array Lists 88 Make Parallel Arrays into Arrays of Objects Figure 13: Avoid Parallel Arrays // Don't do this int[] accountNumbers; double[] balances;

Chapter 7  Arrays and Array Lists 89 Make Parallel Arrays into Arrays of Objects  Use arrays of objects to avoid parallel arrays Figure 14: Reorganizing Parallel Arrays into Arrays of Objects BankAccount[] = accounts;

Chapter 7  Arrays and Array Lists 90 Partially Filled Arrays  Array length is the maximum number of elements in the array  Usually, array is partially filled  Use companion variable to keep track of current size of array  Uniform naming convention is a good idea: final int DATA_LENGTH = 100; double[] data = new double[DATA_LENGTH]; int dataSize = 0;

Chapter 7  Arrays and Array Lists 91 Partially Filled Arrays  Update dataSize as array is filled… data[dataSize] = x; dataSize++;

Chapter 7  Arrays and Array Lists 92 Partially Filled Arrays Figure 15: A Partially Filled Array

Chapter 7  Arrays and Array Lists 93 An Early Internet Worm Figure 16: A "Buffer Overrun" Attack