principles of computer
play

Principles of Computer Become familiar with arrays and array lists - PDF document

Lecture Outline Principles of Computer Become familiar with arrays and array lists Science I Using wrapper classes, auto-boxing Enhanced for loop Prof. Nadeem Abdul Hamid Array algorithms CSC 120 Fall 2005 Lecture Unit 8 -


  1. Lecture Outline Principles of Computer  Become familiar with arrays and array lists Science I  Using wrapper classes, auto-boxing  Enhanced for loop Prof. Nadeem Abdul Hamid  Array algorithms CSC 120 – Fall 2005 Lecture Unit 8 - Arrays  Two-dimensional arrays 1 2 CSC120 — Berry College — Fall 2005 Arrays Constructing Arrays  Many programs need to manipulate (large)  new operator constructs an array collections of related data values  Array reference can be stored in a variable  Type of the array is the element type, followed by []  Would be very inefficient to use a bunch of variables: data1 , data2 , data3 , … double[] data = new double[ 10 ];  Can create arrays of any type (even other arrays)  Array: sequence of values of the same type BankAccount[] accounts = new BankAccount[ 25 ];  To construct an array of 10 f.p. numbers:  Upon array construction, values initialized depending on type new double[ 10 ]  Numbers: 0  Boolean: false  Object references: null 3 4 Accessing Array Elements Array Bounds  Specify array element by integer within square  Index values start at 0 and go up to one less than the array length brackets [ ] data[10] = 29.95; // BOUNDS ERROR data[ 4 ]  To find the number of elements in an array use the  Store values using an assignment statement length field data[2] = 29.95; data.length  Notice numbering  Unlike most other properties of objects, length of arrays is starts at 0 an instance field, not a method (so no parentheses)  Array of length 10 has  Common for loop pattern for processing arrays indices 0 to 9 for ( int i = 0; i < data.length; i++ ) . . . 5 6 1

  2. Initializing Arrays Processing Arrays  Common error: declare an array variable but forget to double[] data = new double[ 10 ]; allocate the actual array . . . double[] data; // should be double[] data = new double[10]; data[0] = 29.95;  Write code to find the maximum and minimum values in the data array  If elements of an array are known already, you can allocate and initialize the array by listing them  Write code to find the average of the data int[] primes = { 2, 3, 5, 7, 11 }; array values  To construct and initialize an unnamed array new int[] { 2, 3, 5, 7, 11 } 7 8 Array Lists Constructing Array Lists  Limitation of primitive arrays: fixed size ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();  ArrayList class lets you manage sequence accounts.add( new BankAccount(1001) ); accounts.add( new BankAccount(1015) ); of objects, like an array, but  Can grow and shrink in size as needed ArrayList<BankAccount> declares an array list of  bank accounts  Has methods for common operations such as inserting/removing elements in the middle of the  Angle brackets indicate BankAccount is a type parameter – can use any other class name there instead sequence  ArrayList class is a generic class: ArrayList<T> collects objects of type T  Import java.util.ArrayList  Cannot use primitive types as type parameters – no ArrayList<int> 9 10 ArrayList Methods ArrayList Example  add(a)  BankAccount.java  adds new object to the end of the array list  ArrayListTester.java  add(i, a)  adds object a at position i (shifts up all other elements ArrayList<BankAccount> accounts = new ArrayList<BankAccount>(); after position i) accounts.add(new BankAccount(1001));  get(i) accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1729));  returns element at the i’th index (starts at 0) accounts.add(1, new BankAccount(1008));  remove(i) accounts.remove(0);  removes element at position i (shifts down elements after System.out.println("size=" + accounts.size()); the removed one) BankAccount first = accounts.get(0); System.out.println("first account number="  size() + first.getAccountNumber());  returns current size of the array list (initially 0) BankAccount last = accounts.get(accounts.size() - 1); System.out.println("last account number=" + last.getAccountNumber()); See Quality Tip 8.1 about untyped array lists 11 12 2

  3. Length and Size Primitive Types and Objects  Java has inconsistent syntax for determining  Cannot directly store primitive types (int, length/size of strings, arrays, array lists: double, char) in array lists  Must first ‘wrap’ them up into objects  Array – ArrayList<Double> data = new ArrayList<Double>(); a.length data.add( new Double(29.95) );  Array list – a.size() double x = data.get(0).doubleValue();  String – a.length() Double d = new Double( 29.95 ); 13 14 Wrapper Classes Auto-boxing  Notice differences in names  Better name: ‘auto-wrapping’ – only in Java 5.0  Wrapper objects can be  Automatic conversion between primitive types and used anywhere objects are corresponding wrapper classes required instead of primitive Double d = 29.95; // same as Double d = new Double(29.95); values double x = d; // same as double x = d.doubleValue(); Double e = d + 1;  Last statement 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 15 16 Arrays vs Array Lists Enhanced for Loop  Arrays  Only available from Java version 5.0 onward  Pros: Efficient (less space, faster access), built-in Java  Shortcut for iterating through sequence of construct - supports primitive types and objects, multi- elements from beginning to end dimensional arrays  Cons: Fixed size, no operations besides index access Enhanced version Traditional version  Array Lists double[] data = . . .; double[] data = . . .;  Pros: Resizable (automatically), provides double sum = 0; double sum = 0; add/insert/remove operations for (int i = 0; i < data.length; i++) { for (double e : data) { double e = data[i]; sum = sum + e;  Cons: Only stores objects, less efficient (especially when sum = sum + e; } using wrapper objects for primitive types), syntax little } more cluttered Read as ‘ for each e in data ’ 17 18 3

  4. Enhanced for with Array Lists Syntax: ‘for each’ loop ArrayList<BankAccount> accounts = . . . ; for ( Type variable : collection ) statement double sum = 0; for (BankAccount a : accounts) { sum = sum + a.getBalance(); Purpose: 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. double sum = 0; for (int i = 0; i < accounts.size(); i++) { BankAccount a = accounts.get(i); sum = sum + a.getBalance();  The ‘for each’ construct has very specific purpose. If you don’t } want to start at the beginning of the collection, or need to traverse the collection in reverse order, use a regular for loop 19 20 Simple Array Algorithms: Simple Array Algorithms: Counting Matches Finding a Value  Check all elements and count the matches  Check all elements until you have found a until you reach the end of the array list. match (return null if no match found) public class Bank public class Bank { { . . . . . . public int count(double atLeast) { public BankAccount find(int accountNumber) { int matches = 0; for (BankAccount a : accounts) { for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) // Found a match if (a.getBalance() >= atLeast) matches++; return a; // Found a match } } return null; // No match in the entire array list return matches; } } . . . . . . private ArrayList<BankAccount> accounts; private ArrayList<BankAccount> accounts; } } 21 22 Simple Array Algorithms: Finding a Maximum/Minimum Two-Dimensional Arrays  Initialize a candidate with the starting  Example: Tic-Tac-Toe board  Rows and columns of values element make up a 2D array or matrix  Compare candidate with remaining elements  Access elements with index pair a[i][j]  Construct by specify dimensions  Update it if you find a larger or smaller value final int ROWS = 3;  (Return null if the collection is empty) final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS];  Results in a 2D array with 9 elements:  Bank.java board[0][0] board[0][1] board[0][2]  BankTester.java board[1][0] board[1][1] board[1][2] board[2][0] board[2][1] board[2][2] 23 24 4

Recommend


More recommend