Question: override the equals method (which means we also need to override hashCode(), see why here). Here is an example of using casting and instanceof to

override the equals method (which means we also need to override hashCode(), see why here). Here is an example of using casting and instanceof to successfully override equals(). Q2 summary: override equals() and hashCode in the simple IntHolder class, so it prints true in the above example
Link for example: https://stackoverflow.com/questions/16497471/casting-in-equals-method
Lab Q2 overriding equals() and hashCode() - in order to compare two objects in java, we use the equals() method. The call to equals looks like this: bool is Equal = objl.equals (obj2); Where obj1 and obj2 are the two objects we want to compare for equality. By default, equals() simply compares the reference value (address) of the two objects. Below is the default behavior of equals (which all classes inherit from Object): public boolean equals (Object obj) { return (this == obj); } By default (without overriding equals()) two references are equal in Java if and only if they both refer to the same object (remember - reference types are any non-primitive type, any class you define in Java is a reference type). Therefore, in the above equals method, the code this == obj simply checks to see if both references have the same address, if so it means they both refer to the same object. We would like to override equals() so when we call obj1.equals(obj2), it will return true if both obj1 and obj2 have the same state, even if they are references to different objects. Consider the following class: class IntHolder { public int x, yi public IntHolder (int x, int y) { this.x = x; this.y = y; } /* @Override public boolean equals (Object obj) { ... your code here... */ } now consider the following code in main: IntHolder intHolderl = new IntHolder (2, 4); IntHolder intHolder2 = new IntHolder (2,4); System.out.println(intHolderl.equals(intHolder2)); // should print 'true' if 'equals()' overridden properly We want this to print true, because even though intHolder 1 and intHolder2 are different objects, they are equal in the sense that they have the same 'state' (their instance variables have the same values). To get this behavior, we need to
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
