Let’s see your code:
public Objeto busca(String nome){
for(Objeto id : MinhaLista){
if(id.getNome().equals(nome)){
return null;
} else {
return id;
}
}
}
When it starts iterating the first element, if the name matches the expected one, it returns null
, and when it does not match returns this object.
This is not right. It always returns in the first iteration! Moreover, it only returns the first element if it nay is what you’re looking for. If it’s what you’re looking for it doesn’t return anything! It makes no sense.
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 avoid 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
contains no elements null
because it doesn’t usually make sense. If it does, you can add a if (id == null) continue;
before this other if
which is already in the code.
You can use it
break
when you find the result.– Lucas Virgili
This code makes no sense and if it is repeating the problem is in the method call
busca
. Note that this will run only once always. In the first interaction, it will fall into one of the two blocks of theif
and in both there is areturn
terminating the method.– Maniero