java 搜索arraylist,在java中ArrayList中搜索
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 missing a return statement.Customer findCust
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 missing a return statement.
Customer findCustomerByid(int id){
boolean exist=false;
if(this.customers.isEmpty()) {
return null;
}
for(int i=0;i
if(this.customers.get(i).getId() == id) {
exist=true;
break;
}
if(exist) {
return this.customers.get(id);
} else {
return this.customers.get(id);
}
}
}
//the customer class is something like that
public class Customer {
//attributes
int id;
int tel;
String fname;
String lname;
String resgistrationDate;
}
解决方案
The compiler is complaining because you currently have the 'if(exist)' block inside of your for loop. It needs to be outside of it.
for(int i=0;i
if(this.customers.get(i).getId() == id){
exist=true;
break;
}
}
if(exist) {
return this.customers.get(id);
} else {
return this.customers.get(id);
}
That being said, there are better ways to perform this search. Personally, if I were using an ArrayList, my solution would look like the one that Jon Skeet has posted.
更多推荐


所有评论(0)