I\'m trying to figure out the best way to search a customer in an ArrayList
by its Id number. The code below is not working; the compiler tells me that I am mis
Even if that topic is quite old, I'd like to add something.
If you overwrite equals
for you classes, so it compares your getId
, you can use:
customer = new Customer(id);
customers.get(customers.indexOf(customer));
Of course, you'd have to check for an IndexOutOfBounds
-Exception, which oculd be translated into a null pointer or a custom CustomerNotFoundException
.
Personally I rarely write loops myself now when I can get away with it... I use the Jakarta commons libs:
Customer findCustomerByid(final int id){
return (Customer) CollectionUtils.find(customers, new Predicate() {
public boolean evaluate(Object arg0) {
return ((Customer) arg0).getId()==id;
}
});
}
Yay! I saved one line!