Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture Notes – Arrays and ArrayLists (Ch 7-8)

Similar presentations


Presentation on theme: "Lecture Notes – Arrays and ArrayLists (Ch 7-8)"— Presentation transcript:

1 Lecture Notes – Arrays and ArrayLists (Ch 7-8)
Yonglei Tao

2 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);

3 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];

4 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?

5 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;

6 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}; }

7 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]);

8 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.

9 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);

10 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” );

11 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

12 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"); }

13 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)

14 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

15 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

16 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

17 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”);

18 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)

19 Wrapper Classes

20 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

21 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

22 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.*;

23 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 /** Constructs a bank with no bank accounts. */ public Bank() { accounts = new ArrayList<BankAccount>(); } 17

24 Class Bank (cont.) 18 /** 19 Adds an account to this bank.
/** Adds an account to this bank. @param a the account to add */ public void addAccount(BankAccount a) { accounts.add(a); } 26 /** Gets the sum of the balances of all accounts in this bank. @return the sum of the balances */ public double getTotalBalance() { double total = 0; for (BankAccount a : accounts) { total = total + a.getBalance(); } return total; } 40

25 Class Bank (cont.) /** Counts the number of bank accounts whose balance is at least a given value. @param atLeast the balance required to count an account @return the number of accounts having least the given balance */ public int countBalancesAtLeast(double atLeast) { int matches = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) matches++; // Found a match } return matches; } 56

26 Class Bank (cont.) 57 /** 58 Finds a bank account with a given number.
/** Finds a bank account with a given number. @param accountNumber the number to find @return the account with the given number, or null if there is no such account */ 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 } 72

27 Class Bank (cont.) /** Gets the bank account with the largest balance. @return the account with the largest balance, or null if the bank has no accounts */ public BankAccount getMaximum() { if (accounts.size() == 0) return null; 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; } 90 }

28 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 { Bank firstBankOfJava = new Bank(); firstBankOfJava.addAccount(new BankAccount(1001, 20000)); firstBankOfJava.addAccount(new BankAccount(1015, 10000)); firstBankOfJava.addAccount(new BankAccount(1729, 15000)); 12 double threshold = 15000; int count = firstBankOfJava.countBalancesAtLeast(threshold); System.out.println("Count: " + count); System.out.println("Expected: 2"); 17

29 Class BankTester (cont.)
int accountNumber = 1015; BankAccount account = firstBankOfJava.find(accountNumber); if (account == null) System.out.println("No matching account"); else System.out.println("Balance of matching account: " account.getBalance()); System.out.println("Expected: 10000"); 26 BankAccount max = firstBankOfJava.getMaximum(); System.out.println("Account with largest balance: " max.getAccountNumber()); System.out.println("Expected: 1001"); } 32 } Program Run: Count: 2 Expected: 2 Balance of matching account: Expected: 10000 Account with largest balance: 1001 Expected: 1001


Download ppt "Lecture Notes – Arrays and ArrayLists (Ch 7-8)"

Similar presentations


Ads by Google