Friday, 27 September 2013

Java ArrayList with condition

Java ArrayList with condition

I have a question about if condition in ArrayList, Please see code:
public class Test {
public static void main(String[] args) {
ArrayList<BankAccount>accounts=new ArrayList<BankAccount>();
BankAccount Mary=new BankAccount(1,50);
BankAccount Lucy=new BankAccount(2,100);
BankAccount Lily=new BankAccount(3,20);
BankAccount Pete=new BankAccount(4,200);
BankAccount Paul=new BankAccount(5,30);
accounts.add(Mary);
accounts.add(Lucy);
accounts.add(Lily);
accounts.add(Pete);
accounts.add(Paul);
double min=accounts.get(0).getBalance();
int poorestPerson=accounts.get(0).getAccountNumber();
for(BankAccount a:accounts){
if(a.getBalance()<min){
poorestPerson=a.getAccountNumber();
}
}
System.out.println("Poorest person is "+poorestPerson);
}
}
The result is always 5, but the correct print should be 3, when I add :
poorestPerson=a.getAccountNumber();
**min=a.getBalance();**
It prints right answer, my question is how does this command vary the
result?Cheers.

No comments:

Post a Comment