Minimum value of objects in ArrayList
Hey All!
I am a newbie in Java but have come across a problem I can't really grasp.
If you can, please enlighten me, as my head got stuck on this issue :)
Alright: assume an ArrayList with objects of class Employee which all have names, id's and salaries. Problem - find the minimum salary.
So, I understand that I need to create a for loop, but here's where things become tricky. I have no problem of finding min/max of INT in Arrays, or longest/shortest strings in ArrayLists, and even max salary in this ArrayList (i.e. for loops).
I do not want to use Collections or similar methods - so where do I do it wrong?
Example:
Code :
int lowest = ArrayList.size();
for(Employee s:ArrayList){
if(s.getSalary()<lowest){
lowest = s.getSalary();
}
}
? - lowest becomes ArrayList.size(), but not the smallest salary.
Re: Minimum value of objects in ArrayList
Simple. Start with some other value for lowest.
The most common idiom is to initialize a int variable that has to receive a minimum to Integer.MAX_VALUE, and to initialize a numeric variable that has to receive a maximum value to 0. In either case, you can also choose to initialize the value to the first value extracted from the collection -- list.get(0).getValue().
db
Re: Minimum value of objects in ArrayList
Darryl.Burke
Thank you!
It all makes sense now, it's all about that value of int variable - fix that and you're good to go! :)