obiettivi del capitolo capitolo 7 array e array list

21
Capitolo 7 array e array list 80 Fondamenti Informatica UNIPD © 2007 1 Obiettivi del capitolo Acquisire familiarità con l’utilizzo di array e array list (vettori ) Studiare le classi involucro, la tecnica di auto- impacchettamento e il ciclo for generalizzato Apprendere gli algoritmi più comuni per gli array Capire come usare array bidimensionali Imparare a scegliere array o vettori nei vostri programmi Realizzare array riempiti solo in parte 80 Fondamenti Informatica UNIPD © 2007 2 Array Sequenza di valori dello stesso tipo Costruisci un array: Memorizza in variabile del tipo double[ ] new double[10] double[] data = new double[10]; Continued… 80 Fondamenti Informatica UNIPD © 2007 3 Array Quando un array viene creato, tutti i valori vengono inizializzati in base al tipo dell’array: Numeri: 0 Boolean: false Riferimenti agli oggetti: null

Upload: others

Post on 24-Apr-2022

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Obiettivi del capitolo Capitolo 7 array e array list

Capitolo 7array e array list

80

Fondamenti Informatica UNIPD © 2007 1

Obiettivi del capitolo

Acquisire familiarità con l’utilizzo di array e array list (vettori ) Studiare le classi involucro, la tecnica di auto-impacchettamento e il ciclo for generalizzato Apprendere gli algoritmi più comuni per gli arrayCapire come usare array bidimensionaliImparare a scegliere array o vettori nei vostri programmiRealizzare array riempiti solo in parte

80

Fondamenti Informatica UNIPD © 2007 2

Array

Sequenza di valori dello stesso tipoCostruisci un array:

Memorizza in variabile del tipo double[ ]

new double[10]

double[] data = new double[10];

Continued…

80

Fondamenti Informatica UNIPD © 2007 3

Array

Quando un array viene creato, tutti i valori vengono inizializzati in base al tipo dell’array:

Numeri: 0 Boolean: false Riferimenti agli oggetti: null

Page 2: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 4

ArraySi usa [ ] per accedere ad un elementodata[2] = 29.95;

80

Fondamenti Informatica UNIPD © 2007 5

DieTester.java

01: /**02: Questo programma registra dieci lanci di un dado.03: */04: public class DieTester05: {06: public static void main(String[] args)07: {08: final int TRIES = 10;09: Die d = new Die(6);

int[] lanci = new int[TRIES];10: for (int i = 0; i < TRIES; i++) { 12: lanci[i] = d.cast();14: }15: System.out.println(lanci);16: }17: }

80

Fondamenti Informatica UNIPD © 2007 6

Array

Per utilizzare il valore memorizzato:

Si ricava la lunghezza dell’array con data.length. (Non è un metodo!) Il valore dell’indice deve essere compreso fra0 e length - 1

System.out.println("The data item is " + data[4]);

80

Fondamenti Informatica UNIPD © 2007 7

Array

Accedere ad un elemento non esistente èun errore

Limitazione: gli array hanno una lunghezza fissa

double[] data = new double[10];data[10] = 29.95; // ERROR

Page 3: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 8

Sintassi 8.1: Costruzione di Array

new nomeTipo [lunghezza]

Esempio:new double[10]

Obiettivo:Costruire un array con un dato numero di elementi

80

Fondamenti Informatica UNIPD © 2007 9

riferimentoAdArray [Indice]

Esempio:data[2]

Obiettivo:Accedere ad un elemento diun array

Sintassi 8.2: Accesso a Elementi di Array

80

Fondamenti Informatica UNIPD © 2007 10

Verifica

1. Quali valori sono presenti nell’array dopo l’esecuzione dei seguenti enunciati? double[] data = new double[10];for (int i = 0; i < data.length; i++) data[i] = i * i;

80

Fondamenti Informatica UNIPD © 2007 11

Verifica

2. Cosa visualizzano i seguenti frammenti di programma? Oppure, se c’è un errore, descrivete l’errore ed indicate se si tratta di un errore di compilazione o di un errore di esecuzione.

1. double[] a = new double[10];System.out.println(a[0]);

2. double[] b = new double[10];System.out.println(b[10]);

3. double[] c;System.out.println(c[0]);

Page 4: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 12

Risposte

1. 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, ma non 100

2.

1. 0 2. Errore di esecuzione: indice di array fuori

dai limiti3. Errore di compilazione: c non è

inizializzata

80

Fondamenti Informatica UNIPD © 2007 13

Array bidimensionali

Costruendo un array bidimensionale, specificate di quante righe o colonne avete bisogno:

Accedete ad elementi con una coppia di indici a[i][j]

final int ROWS = 3;final int COLUMNS = 3;String[][] board = new String[ROWS][COLUMNS];

board[i][j] = "x";

80

Fondamenti Informatica UNIPD © 2007 14

Una scacchiera Tic Tac Toe 80

Fondamenti Informatica UNIPD © 2007 15

Di solito si usano cicli annidati quando si inseriscono o si cercano dati:for (int i = 0; i < ROWS; i++)

for (int j = 0; j < COLUMNS; j++)board[i][j] = " ";

Attraversare array bidimensionali

Page 5: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 16

File TicTacToe.java01: /**02: A 3 x 3 tic-tac-toe board.03: */04: public class TicTacToe05: {06: /**07: Constructs an empty board.08: */09: public TicTacToe()10: {11: board = new String[ROWS][COLUMNS];12: // Fill with spaces13: for (int i = 0; i < ROWS; i++)14: for (int j = 0; j < COLUMNS; j++)15: board[i][j] = " ";16: }17: Segue…

80

Fondamenti Informatica UNIPD © 2007 17

File TicTacToe.java18: /**19: Sets a field in the board. The field must be unoccupied.20: @param i the row index 21: @param j the column index 22: @param 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, such as32: |x o|33: | x |34: | o|35: @return the string representation36: */ Segue…

80

Fondamenti Informatica UNIPD © 2007 18

File TicTacToe.java37: 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: }

80

Fondamenti Informatica UNIPD © 2007 19

File TicTacToeTester.java

01: import java.util.Scanner;02: 03: /**04: This program tests the TicTacToe class by prompting the05: user to set positions on the board and printing out the06: result.07: */08: public class TicTacToeTester09: {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: { Segue…

Page 6: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 20

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: else24: {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: else31: player = "x"; 32: }33: }34: }35: } Segue…

80

Fondamenti Informatica UNIPD © 2007 21

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

80

Fondamenti Informatica UNIPD © 2007 22

Verifica

11. Come si dichiara e si inizializza un array di interi 4 per 4?

12. Come si conta il numero di caselle non occupate nella scacchiera tic-tac-toe?

80

Fondamenti Informatica UNIPD © 2007 23

Risposte

11.

12.

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] == ' ') count++;

Page 7: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 24

Copiare Array: Copiare riferimenti agli array

Copiando una variabile array otterrete un altro riferimento allo stesso array

double[] data = new double[10];// fill array . . .double[] prices = data;

Segue…

80

Fondamenti Informatica UNIPD © 2007 25

Copiare Array: Copiare riferimenti agli array

80

Fondamenti Informatica UNIPD © 2007 26

Copiare = Clonare array

Usate clone per fare una vera copia

double[] prices = (double[]) data.clone();

Segue…

80

Fondamenti Informatica UNIPD © 2007 27

Copiare = Clonare array

Page 8: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 28

Copiare Array: Copiare elementi array

System.arraycopy(from, fromStart, to, toStart, count);

80

Fondamenti Informatica UNIPD © 2007 29

Aggiungere un elemento ad un array

System.arraycopy(data, i, data, i + 1, data.length - i - 1);data[i] = x;

80

Fondamenti Informatica UNIPD © 2007 30

Rimuovere un elemento da un array

System.arraycopy(data, i + 1, data, i, data.length - i - 1);

80

Fondamenti Informatica UNIPD © 2007 31

Ingrandire un array

double[] newData = new double[2 * data.length];

System.arraycopy(data, 0, newData, 0, data.length);

data = newData;

Se l’array è pieno e avete bisogno di più spazio, potete ingrandirlo:

1. Creare un nuovo array più grande.

2. Copiare tutti gli elementi nel nuovo array

3. Salvare il riferimento al nuovo array nella variabile array

Page 9: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 32

Ingrandire un array 80

Fondamenti Informatica UNIPD © 2007 33

Verifica

13. Come si aggiungono o si eliminano elementi in una posizione intermedia di un vettore?

14. Perché, quando non c’è più spazio in un array, ne raddoppiamo la dimensione invece di aumentarla di un’unità?

80

Fondamenti Informatica UNIPD © 2007 34

Risposte

13. Usate I metodi insert e remove. 14. Perché è uno spreco di tempo,

bisognerebbe ripetere il processo ogni volta che si aggiunge un elemento.

80

Fondamenti Informatica UNIPD © 2007 35

Trasformare array paralleli in array di oggetti

// Don't do thisint[] accountNumbers;double[] balances;

Page 10: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 36

Trasformare array paralleli in array di oggetti

Evitate array paralleli array di oggetti:

BankAccount[] = accounts;

80

Fondamenti Informatica UNIPD © 2007 37

Array riempiti solo in parte

Lunghezza di un array = numero massimo di elementi in un arrayDi solito è riempito solo in parte Necessita di una variabile associata per tenere traccia della dimensione correnteUniformate I nomi:final int DATA_LENGTH = 100;double[] data = new double[DATA_LENGTH];int dataSize = 0;

Segue…

80

Fondamenti Informatica UNIPD © 2007 38

Array riempiti solo in parte

Aggiornate dataSize quando l’array èpieno:data[dataSize] = x;dataSize++;

80

Fondamenti Informatica UNIPD © 2007 39

Array riempiti solo in parte

Page 11: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 40

Buffer over-run 80

Fondamenti Informatica UNIPD © 2007 41

Vettori

La classe ArrayList controlla una serie di oggettiPuò crescere e restringersi in base alle necessitàLa classe ArrayList fornisce metodi per svolgere le operazioni più comuni, come l’inserimento o la rimozione di elementi

Continued…

80

Fondamenti Informatica UNIPD © 2007 42

Vettori

La classe ArrayList è una classe generica: ArrayList<T> contiene oggetti del tipo T:

Il metodo size restituisce la dimensione attuale di un vettore

ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();accounts.add(new BankAccount(1001));accounts.add(new BankAccount(1015));accounts.add(new BankAccount(1022));

80

Fondamenti Informatica UNIPD © 2007 43

Ricavare elementi di un vettore

Si usa il metodo get

L’indice parte da 0

Se l’indice è fuori dai valori, risulta un errore di limiti

BankAccount anAccount = accounts.get(2); // ricava il terzo elemento di un vettore

Page 12: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 44

Ricavare elementi di un vettore

Errori di limiti più comuni:

int i = accounts.size();anAccount = accounts.get(i); // Error// legal index values are 0. . .i-1

80

Fondamenti Informatica UNIPD © 2007 45

Aggiungere e rimuovere elementi

set sovrascrive un elemento esistente

add aggiunge un nuovo valore nella posizione indicata

remove rimuove l’elemento nella posizione indicata

Continued…

BankAccount anAccount = new BankAccount(1729);accounts.set(2, anAccount);

accounts.add(i, a)

Accounts.remove(i)

80

Fondamenti Informatica UNIPD © 2007 46

Aggiungere e rimuovere elementi

80

Fondamenti Informatica UNIPD © 2007 47

File: ArrayListTester.java

01: import java.util.ArrayList;02: 03: /**04: This program tests the ArrayList class.05: */06: public class ArrayListTester07: {08: public static void main(String[] args)09: {10: ArrayList<BankAccount> accounts 11: = new ArrayList<BankAccount>();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);

jcreator

Page 13: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 48

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: }

80

Fondamenti Informatica UNIPD © 2007 49

File: BankAccount.java01: /**02: A bank account has a balance that can be changed by 03: deposits and withdrawals.04: */05: public class BankAccount06: { 07: /**08: Constructs a bank account with a zero balance09: @param anAccountNumber the account number for this account10: */11: public BankAccount(int anAccountNumber)12: { 13: accountNumber = anAccountNumber;14: balance = 0;15: }16:

80

Fondamenti Informatica UNIPD © 2007 50

File: BankAccount.java17: /**18: Constructs a bank account with a given balance19: @param anAccountNumber the account number for this account20: @param initialBalance the initial balance21: */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.30: @return the account number31: */32: public int getAccountNumber()33: { 34: return accountNumber;35: }

Continued…

80

Fondamenti Informatica UNIPD © 2007 51

File: BankAccount.java36: 37: /**38: Deposits money into the bank account.39: @param amount the amount to deposit40: */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.49: @param amount the amount to withdraw50: */51: public void withdraw(double amount)52: { 53: double newBalance = balance - amount;54: balance = newBalance;

Continued…

Page 14: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 52

File: BankAccount.java55: }56: 57: /**58: Gets the current balance of the bank account.59: @return the current balance60: */61: public double getBalance()62: { 63: return balance;64: }65:66: private int accountNumber;67: private double balance;68: }

Outputsize=3first account number=1008last account number=1729

80

Fondamenti Informatica UNIPD © 2007 53

Verifica

3. Come si costruisce un array di 10 stringhe? E un vettore di stringhe?

4. Cosa contiene names dopo l’esecuzione dei seguenti enunciati?

ArrayList<String> names = new ArrayList<String>();names.add("A");names.add(0, "B");names.add("C");names.remove(1);

80

Fondamenti Informatica UNIPD © 2007 54

Risposte

3.

4. names contiene le stringhe "B" e "C" alle posizioni 0 e 1

new String[10];new ArrayList<String>();

80

Fondamenti Informatica UNIPD © 2007 55

Involucri

Non si possono inserire tipi primitividirettamente in vettori, devono esseretrasformati in oggetti classi involucroArrayList<Double> data = new ArrayList<Double>();data.add(29.95);double x = data.get(0);

Page 15: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 56

Involucri

classi involucro per tutti i tipi primitivi

80

Fondamenti Informatica UNIPD © 2007 57

Auto-impacchettamento

Auto-impacchettamento: a partire da Java 5.0, la conversione tra tipi primitivi e le corrispondenti classi involucro è automatica

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

80

Fondamenti Informatica UNIPD © 2007 58

Auto-impacchettamentoL’ auto-impacchettamento lavora anche all’interno di espressioni aritmetiche

Significati:Converti d in un valore di tipo doubleAggiungi 1 Impacchetta il risultato in un nuovo oggetto di tipo Double

Memorizza in e il riferimento all’oggetto involucro appena creato

Double e = d + 1;

80

Fondamenti Informatica UNIPD © 2007 59

Verifica

5. Qual è la differenza fra i tipi double e Double?

6. Se data è un esemplare di ArrayList<Double> con dimensione maggiore di zero, come si aggiunge un’unità al valore memorizzato nell’elemento di indice zero?

Page 16: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 60

Risposte

5. double è uno degli otto tipi primitivi. Double è un tipo di classe.

6. data.set(0, data.get(0) + 1);

80

Fondamenti Informatica UNIPD © 2007 61

Il ciclo for generalizzato

double[] data = . . .;double sum = 0;for (double e : data) {

sum = sum + e;}

double[] data = . . .;double sum = 0;for (int i = 0; i < data.length; i++) {

double e = data[i];sum = sum + e;

}

80

Fondamenti Informatica UNIPD © 2007 62

Il ciclo for generalizzato

Funziona anche per ArrayLists :

ArrayList<BankAccount> accounts = . . . ;double sum = 0;for (BankAccount a : accounts){

sum = sum + a.getBalance();}

80

Fondamenti Informatica UNIPD © 2007 63

Il ciclo for generalizzato

E’ equivalente al seguente ciclo forordinario:

double sum = 0;for (int i = 0; i < accounts.size(); i++){

BankAccount a = accounts.get(i);sum = sum + a.getBalance();

}

Page 17: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 64

Sintassi 8.3: Il ciclo for generalizzato

for (Type variable : collection)statement

Esempio:for (double e : data)

sum = sum + e;

Obiettivo:Eseguire un ciclo avente un’iterazione per ogni elemento appartenentead una raccolta. All’inizio di ciascuna iterazione viene assegnato allavariabile l’elemento successivo della raccolta, poi viene eseguitol’enunciato.

80

Fondamenti Informatica UNIPD © 2007 65

Verifica

7. Scrivi un ciclo for generalizzato che visualizzi tutti gli elementi dell’array data

8. Perchè non è ragionevole utilizzare un ciclo for generalizzato al posto del seguente ciclo ordinario?

for (int i = 0; i < data.length; i++) data[i] = i * i;

80

Fondamenti Informatica UNIPD © 2007 66

Risposte

7.

8. Il ciclo scrive un valore data[i]. Il ciclofor non ha l’indice variabile i.

for (double x : data) System.out.println(x);

80

Fondamenti Informatica UNIPD © 2007 67

Controlla tutti gli elementi e conta le occorrenze di un valore fino alla fine dell’arraypublic 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;}

Semplici algoritmi per vettori: contare occorrenze di un valore

Page 18: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 68

Semplici algoritmi per vettori: Trovare un valore

Controllate tutti gli elementi finché trovate un valore.

public class Bank {public BankAccount find(int accountNumber){

for (BankAccount a : accounts){ // Found a match

if (a.getAccountNumber() == accountNumber)return a;

}return null; // No match in the entire array list

}…

private ArrayList<BankAccount> accounts;}

80

Fondamenti Informatica UNIPD © 2007 69

Scegliete un candidato come valore massimo Confrontate il candidato con gli altri elementi Sostituitelo se trovate un valore maggiore o minore

Segue…

Semplici algoritmi per vettori : Trovare il massimo o il minimo

80

Fondamenti Informatica UNIPD © 2007 70

Esempio: 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;

Semplici algoritmi per vettori : Trovare il massimo o il minimo

80

Fondamenti Informatica UNIPD © 2007 71

Funziona solo se c’è almeno un elemento nella lista degli arraySe la lista è vuota, il metodo restituisce null

if (accounts.size() == 0) return null;BankAccount largestYet = accounts.get(0);. . .

Semplici algoritmi per vettori : Trovare il massimo o il minimo

Page 19: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 72

File Bank.java01: import java.util.ArrayList;02: 03: /**04: This bank contains a collection of bank accounts.05: */06: public class Bank07: { 08: /**09: Constructs a bank with no bank accounts.10: */11: public Bank()12: {13: accounts = new ArrayList<BankAccount>();14: }15: 16: /**17: Adds an account to this bank.18: @param a the account to add19: */ Segue…

jcreator

80

Fondamenti Informatica UNIPD © 2007 73

File Bank.java20: 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.27: @return the sum of the balances28: */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: Segue…

80

Fondamenti Informatica UNIPD © 2007 74

File Bank.java39: /**40: Counts the number of bank accounts whose balance is at41: least a given value.42: @param atLeast the balance required to count an account43: @return the number of accounts having least the given // balance44: */45: public int count(double atLeast)46: {47: int matches = 0;48: for (BankAccount a : accounts)49: {50: if (a.getBalance() >= atLeast) matches++; // Found // a match51: }52: return matches;53: }54:

Segue…

80

Fondamenti Informatica UNIPD © 2007 75

File Bank.java55: /**56: Finds a bank account with a given number.57: @param accountNumber the number to find58: @return the account with the given number, or null 59: if there is no such account60: */61: public BankAccount find(int accountNumber)62: {63: for (BankAccount a : accounts)64: {65: if (a.getAccountNumber() == accountNumber) // Found a match66: return a;67: } 68: return null; // No match in the entire array list69: }70: Segue…

Page 20: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 76

File Bank.java71: /**72: Gets the bank account with the largest balance.73: @return the account with the largest balance, or 74: null if the bank has no accounts75: */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<BankAccount> accounts;90: }

80

Fondamenti Informatica UNIPD © 2007 77

File BankTester.java01: /**02: This program tests the Bank class.03: */04: public class BankTester05: {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);

Segue…

80

Fondamenti Informatica UNIPD © 2007 78

File BankTester.java16:17: int accountNumber = 1015;18: BankAccount a = firstBankOfJava.find(accountNumber);19: if (a == null) 20: System.out.println("No account with number "

+ accountNumber);21: else22: System.out.println("Account with number "

+ accountNumber23: + " 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: }

Segue…

80

Fondamenti Informatica UNIPD © 2007 79

File BankTester.java

Output2 accounts with balance >= 15000.0Account with number 1015 has balance 10000.0Account with number 1001 has the largest balance.

Page 21: Obiettivi del capitolo Capitolo 7 array e array list

80

Fondamenti Informatica UNIPD © 2007 80

Verifica

9. Come si comporta il metodo find se esistono due conti bancari con il numero di conto uguale al numero cercato?

10. Si potrebbe usare il ciclo "for" generalizzato nel metodo getMaximum?

80

Fondamenti Informatica UNIPD © 2007 81

Risposte

9. Restituisce il primo che trova 10. Sì, ma il primo confronto fallirà sempre