You must include the method equals
and hashCode
, overwriting them in your Contato
class:
public class Contato {
private String nome;
private String email;
private int telefone;
/*getters e setters*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + telefone;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contato other = (Contato) obj;
if (telefone != other.telefone)
return false;
return true;
}
}
Why ??
So your edit and fetch methods will become extremely simpler because ArrayList implements methods that allow you to find the object in a collection much better.
Edit method
@Override
public void editar(Contato contato) {
if(contato == null){
throw new IllegalArgumentException("contato nao pode ser nulo");
}
int index = contatos.indexOf(contato);
if(index > -1){
contatos.add(index, contato);
}
}
Because your Contact class now implements the equals method we can quickly find the index and simply replace it in the ArrayList. There is a problem here that the fact that an ArrayList allows for duplicate items, but will catch there.
Search method:
@Override
public Contato buscar(int contato) {
List<Contato> contatosAchados = contatos
.stream()
.filter(c -> c.telefone == contato)
.collect(Collectors.toList());
if(!contatosAchados.isEmpty()){
return contatosAchados.get(0);
}
return null;
}
What about duplicate contacts in the ArrayList?
That is, ArrayList, allows duplicate elements, in this case, contacts to private and in method add a knife to method contains
checking if the contact already exists, if it already exists, you do not add, if there is not yes, you add it:
@Override
public void adicionar(Contato contato) {
if(!contatos.contains(contato))
this.contatos.add(contato);
}
Again, the equals
method allows you to use contains to check if it already exists.
Final considerations
Consider not referencing a Collection by its concrete implementation, but by its interface, that is, instead of
ArraList<Contato> contatos;
Use:
List<Contato> contatos = new ArrayList<>();
Should the Contacts attribute really be public?
I do not know what you're doing, but I recommend that you do not allow any class to access your members in this way, try switching to private, and provide an access method, so you can encapsulate and protect your data.