Let's look at your code:
public Objeto busca(String nome){
for(Objeto id : MinhaLista){
if(id.getNome().equals(nome)){
return null;
} else {
return id;
}
}
}
When it starts to iterate the first element, if the name matches that expected, it returns null
, and when it does not match this object returns.
This is not right. It always returns in the first iteration! Also, it only returns the first element if it not is what you are looking for. If it's what you're looking for it will not return anything! This is pointless.
I think what you wanted is this:
public Objeto busca(String nome){
for(Objeto id : MinhaLista){
if(id.getNome().equals(nome)){
// Achou o que queria, retorna.
return id;
}
}
return null; // Tentou todos e não achou nenhum, desiste.
}
As suggested by Felipe Fonseca in a comment, it is worth treating null
s and avoiding NullPointerException
s:
public Objeto busca(String nome){
Objects.requireNonNull(nome, "O nome do objeto a buscar deve ser informado.");
for(Objeto id : MinhaLista){
if(nome.equals(id.getNome())){
// Achou o que queria, retorna.
return id;
}
}
return null; // Tentou todos e não achou nenhum, desiste.
}
I'm assuming that MinhaLista
does not contain null
elements in it because this does not usually make sense. If this occurs, you can add if (id == null) continue;
before this other if
that is already in the code.