File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals() in java.util and equals() in Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals() in java.util and equals() in Object" Watch "equals() in java.util and equals() in Object" New topic

equals() in java.util and equals() in Object

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
1. What is the difference in equals() in java.util and equals() in Object class?
2. Why equals() in java.util overrides equals() in Object ?.
3. Code:
Box b1 = new Box();
Box b2 = new Box();
b1.l = 5 ; b2.l = 5 ; // l is public instance var in box class
b1.equals(b2) is false // Because 2 different objects hence 2 different references stored in b1 and b2. (Please correct me if iam wrong)
Integer i1 = new Integer(5);
Integer i2 = new Integer(5);
i1.equals(i2) returns true!. Why? If I apply same logic as above, why i1.equals(i2) returns true? OR is implementation of equals method for wrapper class different?
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
yes. Your doubt is correct. The equals(Object obj) of Box is the one which is inherited from Object class. Box class DOES NOT override this method to do something useful comparion. So all that is done by the inherited .equals(Object obj) method is just compare the 2 REFS ARE SAME which is the default implementation from Object class.
On the other hand, the Integer class DOES OVERRIDE this method and compares the content on the Integer objects. So the results are different for the above 2 case mentioned by you.
For your information, the javax.swing package is NOT objectives of SCJP2 Exam. So I am leaving this thread if any other discussion other than java.swing package follows.
maha anna
I agree. Here's the link:
subject: equals() in java.util and equals() in Object
jQuery in Action, 3rd edition