1
I’m learning to use the equals()
and hashCode()
, and I was taught that Eclipse overwrites this method for us. But I’m trying to buy two attributes to tell if one object is the same as the other.
Better example: If a product has the same code, but its size is different, they should be considered different objects. I’m using HashMap
for this implementation.
The Equals()
and HashCode()
are like this:
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((super.getCodigo() == null) ? 0 : super.getCodigo().hashCode());
result = prime * result + ((getTamanho() == null) ? 0 : getTamanho().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ProdutoComTamanho other = (ProdutoComTamanho) obj;
if (super.getCodigo() == null) {
if (other.getCodigo() != null)
return false;
} else
return false;
if (getTamanho() == null) {
if (other.getTamanho() != null)
return false;
} else if (!getTamanho().equals(other.getTamanho()) && !super.getCodigo().equals(other.getCodigo()))
return false;
return true;
}
When I test the application it doesn’t consider them as different objects, only when I change the product code.