You must include the method equals
and hashCode
, writing in their class Contato
:
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??
Thus, your methods edit and search will become extremely simple, because Arraylist implements methods that allow you to find in a collection, the object in a much better way.
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);
}
}
Why your Contact class now implements the equals method we can quickly find the Input and simply replace in Arraylist. There is a problem here that Oand an Arraylist allow duplicate items, but we will get 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;
}
And in the case of duplicate contacts in Arraylist?
That is, the Arraylist, allows duplicated elements, in this case contacts to private and in the method add a call to the method contains
checking if the contact already exists, if it already exists, you do not add, if it does not exist there yes, you add it:
@Override
public void adicionar(Contato contato) {
if(!contatos.contains(contato))
this.contatos.add(contato);
}
Again, the method equals
allows you to use contains to check if it already exists.
Final considerations
Consider not referring to a Collection for its concrete implementation but rather for its interface, that is, instead of
ArraList<Contato> contatos;
Utilize:
List<Contato> contatos = new ArrayList<>();
The Contacts Attribute really should be public?
I don’t know what you’re doing, but I recommend that you don’t allow any class to access your members this way, try switching to private, and provide an access method, so you can encapsulate and protect your data.
Your method
buscar
gets aint
. What thisint
is for classContato
? It’s the contact phone, the position on theArrayList
or something else? For the methodeditar
work, it is also necessary to know this before.– Victor Stafusa