Lecture Notes – Arrays and ArrayLists (Ch 7-8) Yonglei Tao
Arrays Hold sequences of values of primitive types or objects When an array is created, its values are initialized zero, false, or null int [] scores; scores = new int [10]; for (int i = 0; i < scores.length; i++) scores[i] = i * i; for (int n: scores) // a “for each” loop System.out.println (n);
Arrays (Cont.) A two-dimensional array String[] names = {“Ed”, “Bob”, “Cindy”}; System.out.println( names[0] ); if ( names[0].equals(“Ed”)) … String[] list = new String[5]; list[0] = new String(“Tom”); … A two-dimensional array int rows = 10, cols = 20; int [][] table = new int[rows][cols];
Split String into Array String s = “John Doe; 25; Spring Lake”; String[] tokens = s.split(“;”); if (tokens.length == 3) { String name = tokens[0]; int age = Integer.parseInt(tokens[1]); String city = tokens[2]; … } Other ways to do?
Linear Search /** Finds a value in an array, using the linear search algorithm. @param v the value to search @param a the array to be searched @return the index at which the value occurs, or -1 if it does not occur in the array */ public int search(int v, int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] == v) return i; } return -1;
Discussion Given the number of days from the new year’s day, how to find out in which month it falls? int findMonth (int numOfDays) { int [] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; }
Partially Filled Arrays - Loading double [] values = new double [20]; int numValues = 0; Scanner scan = new Scanner(System.in); while (scan.hasNextDouble() && numValues < values.length) { values[numValues] = scan.nextDouble(); numValues ++; } for (int i = 0; i < numValues; i++) { System.out.println(values[i]);
Ordered Arrays - Insert while (scan.hasNextDouble() && numValues < values.length) { int newValue = scan.nextDouble(); int pos = 0; while ( values[pos] > newValue ) pos++; for (int i = numValues ; i > pos; i--) values[i] = values[i - 1]; values[pos] = newValue; numValues ++; } Consider a general case first and then make sure it works for special cases as well.
Common Array Algorithm – Array Copy double[] values = new double[6]; . . . // Fill array values double[] prices = values; ? double[] prices = Arrays.copyOf(values, values.length); values = Arrays.copyOf(values, 2 * values.length);
Class ArrayList A sequence of objects Can grow and shrink as needed A generic class with a type parameter ArrayList<String> classlist = new ArrayList<String> (); classlist.add ( “Ed” ); classlist.add ( “Bob” ); classlist.add ( “Cindy” );
ArrayList (Cont.) for (int i = 0; i < classlist.size(); i++ ) { String name = classlist.get(i); System.out.println (name); // Ed, Bob, Cindy } for ( String name: classlist ) System.out.println (name); classlist.set (1, “Tim”); // Ed, Tim, Cindy classlist.add (1, “Ron”); // Ed, Ron, Tim, Cindy classlist.remove (2); // Ed, Ron, Cindy
ArrayList Algorithm - Search int pos = 0; boolean found = false; while ( pos < classlist.size() && !found ) { if ( classlist.get(pos) > 100 ) found = true; else pos++; } if ( found ) { System.out.println("Position: " + pos); } { System.out.println("Not found"); }
Arrays vs. ArrayLists When do you use which? Element type Number of elements Basic operations Locate insert (at the front, in the middle, at the end) delete (the first, a middle one, the last)
Classes Each represents an entity in the application domain Keeps its information Provides operations to process the information Objects are instances of a class Members instance variables private (instance) methods private (instance) methods public
Method Parameter // a method call // method definition obj.doIt ( num, name ); // method definition public void doIt ( int n, String s ) { n += 4; s = “Mr. “ + s; } Every thing is passed by value “Tom” 6 6
Method Parameter (Cont.) obj.update ( num, book ); System.out.println(“Price is “ + book.getPrice()); … public void update ( int n, Book b ) { n = n + 10; b.setPrice(110.50); } “Big Java” 125.50
Overloaded Methods // Methods of class MyClass public void doIt (int n) { … } public void doIt (char c) { … } public void doIt (int n, String s) { … } // Method calls MyClass obj = new MyClass(); obj.doIt(5); obj.doIt(‘a’); obj.doIt(10, “xyz”);
Static Members of a Class Instance variable One copy per object Static variable One copy per class Static Method Operating on class-wide data Examples Integer.MAX_VALUE, Integer.MIN_VALUE Math.pow(x, y), Math.sqrt(x)
Wrapper Classes
Auto Boxing and Unboxing int n = 25; Integer num = n; // same as num = new Integer (n); Double rate = 5.25; double d = rate; rate = rate + i; Boolean isDone = new Boolean(false); ArrayList<Double> values = new ArrayList<Double>(); values.add(29.95); double x = values.get(0); // inefficient
Packages in Java Package Purpose Sample Class Language support java.lang Language support Math java.util Utilities Random java.io Input and output PrintStream java.awt Abstract Windowing Toolkit Color java.applet Applets Applet java.net Networking Socket java.sql Database Access ResultSet javax.swing Swing user interface JButton omg.w3c.dom Document Object Model for XML documents Document
Packages - Organizing related classes To put classes in a package package cis500.proj1; public class MyClass { ... } To use class with importing import cis500.proj1.MyClass; Or import cis500.proj1.*;
Bank class stores an array list of bank accounts Class Bank Bank class stores an array list of bank accounts 1 import java.util.ArrayList; 2 3 /** 4 This bank contains a collection of bank accounts. 5 */ 6 public class Bank 7 { 8 private ArrayList<BankAccount> accounts; 9 10 /** 11 Constructs a bank with no bank accounts. 12 */ 13 public Bank() 14 { 15 accounts = new ArrayList<BankAccount>(); 16 } 17
Class Bank (cont.) 18 /** 19 Adds an account to this bank. 18 /** 19 Adds an account to this bank. 20 @param a the account to add 21 */ 22 public void addAccount(BankAccount a) 23 { 24 accounts.add(a); 25 } 26 27 /** 28 Gets the sum of the balances of all accounts in this bank. 29 @return the sum of the balances 30 */ 31 public double getTotalBalance() 32 { 33 double total = 0; 34 for (BankAccount a : accounts) 35 { 36 total = total + a.getBalance(); 37 } 38 return total; 39 } 40
Class Bank (cont.) 41 /** 42 Counts the number of bank accounts whose balance is at 43 least a given value. 44 @param atLeast the balance required to count an account 45 @return the number of accounts having least the given balance 46 */ 47 public int countBalancesAtLeast(double atLeast) 48 { 49 int matches = 0; 50 for (BankAccount a : accounts) 51 { 52 if (a.getBalance() >= atLeast) matches++; // Found a match 53 } 54 return matches; 55 } 56
Class Bank (cont.) 57 /** 58 Finds a bank account with a given number. 57 /** 58 Finds a bank account with a given number. 59 @param accountNumber the number to find 60 @return the account with the given number, or null if there 61 is no such account 62 */ 63 public BankAccount find(int accountNumber) 64 { 65 for (BankAccount a : accounts) 66 { 67 if (a.getAccountNumber() == accountNumber) // Found a match 68 return a; 69 } 70 return null; // No match in the entire array list 71 } 72
Class Bank (cont.) 73 /** 74 Gets the bank account with the largest balance. 75 @return the account with the largest balance, or null if the 76 bank has no accounts 77 */ 78 public BankAccount getMaximum() 79 { 80 if (accounts.size() == 0) return null; 81 BankAccount largestYet = accounts.get(0); 82 for (int i = 1; i < accounts.size(); i++) 83 { 84 BankAccount a = accounts.get(i); 85 if (a.getBalance() > largestYet.getBalance()) 86 largestYet = a; 87 } 88 return largestYet; 89 } 90 }
Class BankTester 1 /** 2 This program tests the Bank class. 3 */ 1 /** 2 This program tests the Bank class. 3 */ 4 public class BankTester 5 { 6 public static void main(String[] args) 7 { 8 Bank firstBankOfJava = new Bank(); 9 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 count = firstBankOfJava.countBalancesAtLeast(threshold); 15 System.out.println("Count: " + count); 16 System.out.println("Expected: 2"); 17
Class BankTester (cont.) 18 int accountNumber = 1015; 19 BankAccount account = firstBankOfJava.find(accountNumber); 20 if (account == null) 21 System.out.println("No matching account"); 22 else 23 System.out.println("Balance of matching account: " 24 + account.getBalance()); 25 System.out.println("Expected: 10000"); 26 27 BankAccount max = firstBankOfJava.getMaximum(); 28 System.out.println("Account with largest balance: " 29 + max.getAccountNumber()); 30 System.out.println("Expected: 1001"); 31 } 32 } Program Run: Count: 2 Expected: 2 Balance of matching account: 10000.0 Expected: 10000 Account with largest balance: 1001 Expected: 1001