Equals and Hashcode

Asked

Viewed 273 times

0

Hello! I have a conceptual question. I have a method readDao(table) within the Object (access to the database) that returns a Hashset called resultRead with all objects in the database of that table. I also have a method insertRule(Object obj) within an Objectrule(business rule), which executes an Objectdao method, after the following verification:

 if (!resultadoRead.contains(obj)) {

 // executa a inserção do objeto no banco de dados.
 ObjectDAO.insertDAO(obj);
 }

My question is: For contains to work, do I need to implement the hashset and equals in the Object or DAO class? because in the DAO class, there are no attributes, only methods. Attributes belong to the Object.

Do I use inheritance? another way of checking? I abandon java because this question is very stupid?

1 answer

1


In theory you would not need to overwrite these methods for contains to work. By default, the contains() will call the equals() of the object passed by parameter which in turn will use the hashCode() to make the comparison. Again, in theory this should already be working. If you really need to change the behavior of these methods, it is necessary to effect the change within the structure of the object and not in its DAO class, after all it is the object that is being compared.

  • perfect explanation. Doubt clarified! Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.