7

I am creating a many-to-many mapping of two object classes. Do I need to write hashCode() and equals() methods; if so, does the netbeans automatically generated code help?

Pablo
  • 3,655
  • 2
  • 30
  • 44
Yash
  • 87
  • 1
  • 11
  • you will need `equals` and `hashCode` only when you're performing comparing two objects. – eatSleepCode Jul 07 '16 at 09:58
  • "Does it need hashcode and equals method" If you mean "do *I* have to implement them", well, it depends on what you're trying to do; see [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java). – Andy Turner Jul 07 '16 at 09:59
  • Since you're using `ManyToMany` mapping, you're one of the parameter will be `Collection` of objects, so technically you will need equals and hashcode method. And hence you will need to decide the implementation of `equals` method and perhaps you can use generated `hashCode` method. – eatSleepCode Jul 07 '16 at 10:03
  • Re-worded for grammar. This question could still do with some sample code to help illustrate what you're doing (for example, in which class you implement the methods). – Toby Speight Jul 07 '16 at 11:38

3 Answers3

10

Yes it can!

Simply right click within the class where the objects have been created and choose insert code. A small menu titled "Generate" will pop up with various options, among them is equals() and hashCode(), select it and presto, NetBeans generates the code override for you. Test out the equals method and it will work this time.

NB. When you select "equals() and hashCode()" a Dialogue box appears, just check the boxes on both sides for all the variables you want dealt with. See the image below:

Generate equals() and hashCode on NetBeans

Wachaga Mwaura
  • 3,310
  • 3
  • 28
  • 31
1

Yes, you can use the IDE generated hashcode for comparing two instances. It will suffice your case what matters more is the equals method, pay attention to the parameters that are compared for equality. The auto generated code will compare all the parameters but you may need only few parameters for identifying it uniquely.

Let's say if you need to see if the record read from DB is of the same entity just compare the primary key in equals method. Choosing an equality criteria is totally you discretion.

Naresh Kumar
  • 673
  • 7
  • 17
1

In NetBeans 8.2, the name of the right click menu option is "Insert Code", after you right click on the class or hit Alt-Insert choose "equals and hashCode..."

Insert Code

equals and hashCode

Matt
  • 688
  • 5
  • 12