The result of comparing objects is done through the methods hashCode() and equals(), class Object. Therefore, to make the comparison your way you must write these methods in your class Produto.
Creating a Product class to my liking (since you didn’t say the attributes names), would look something like this:
Product
public class Produto {
int idProduto;
String nomeProduto;
//getters and setters
@Override
public int hashCode() {
//deve ser o mesmo resultado para um mesmo objeto, não pode ser aleatório
return this.idProduto;
}
@Override
public boolean equals(Object obj) {
//se nao forem objetos da mesma classe sao objetos diferentes
if(!(obj instanceof Produto)) return false;
//se forem o mesmo objeto, retorna true
if(obj == this) return true;
// aqui o cast é seguro por causa do teste feito acima
Produto produto = (Produto) obj;
//aqui você compara a seu gosto, o ideal é comparar atributo por atributo
return this.idProduto == produto.getIdProduto() &&
this.nomeProduto.equals(produto.getNomeProduto());
}
}
The method hashCode is used to expedite the search in Collections, and must always return the same value to the same object, in the above case I preferred to return the idProduto for if the idProduto it is different neither to go to the equals(), for surely he will return false.
Don’t forget that modern Ides (Eclipse, Intellij Idea) can automatically generate the equals and hashcode for you.
– Ravi Wallau