Java Reference
In-Depth Information
{
int matches = 0;
for (BankAccount a : accounts)
{
if (a.getBalance() >= atLeast) matches++;
// Found a match
}
return matches;
}
. . .
private ArrayList<BankAccount> accounts;
}
7.5.2 Finding a Value
Suppose you want to know whether there is a bank account with a particular
account number in your bank. Simply inspect each element until you find a match
or reach the end of the array list. Note that the loop might fail to find an answer,
namely if none of the accounts match. This search process is called a linear search
through the array list.
To find a value in an array list, check all elements until you have found a match.
public class Bank
{
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
}
. . .
}
Note that the method returns null if no match is found.
Search WWH ::




Custom Search