Equals e hashCode

3 respostas
joca_java

Pessoal… o que seria uma implementação correta do contrato entre equals e hashCode???

Poderiam dar um exemplo??

Valeu!! []´s

3 Respostas

ViniGodoy

Leia esse tópico:
http://www.guj.com.br/posts/list/52485.java#276120

E o capítulo do livro descrito nele.

fabim
public int hashCode() {
   return -1;
}

public boolean equals(Object o) {

   if ( o instanceof Cliente && ((Cliente)o).getId() == this.getId() )
      return true;
   else
      return false;

}

Perceba que correto nao quer dizer eficiente

ViniGodoy

Não é a toa que o Java diz explicitamente (o final foi negritado por mim):
It is not required that if two objects are unequal according to the java.lang.Object.equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Criado 23 de janeiro de 2008
Ultima resposta 23 de jan. de 2008
Respostas 3
Participantes 3