Simple Array Algorithms: Counting Matches
Check all elements and count the matches until you reach the end of the array list.
public 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;
}
Simple Array Algorithms: Finding a Value
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
}
. . .
}
Simple Array Algorithms: Finding the Maximum or Minimum
Initialize a candidate with the starting element
Compare candidate with remaining elements
Update it if you find a larger or smaller value
Example:
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;
Works only if there is at least one element in the array list . . .
If list is empty, return null:
if (accounts.size() == 0) return null;
BankAccount largestYet = accounts.get(0);
. . .
What does the find method do if there are two bank accounts with a matching account number?
Answer:
It returns the first match that it finds.
Would it be possible to use a "for each" loop in the getMaximum method?
Answer: Yes, but the first comparison would always fail.