Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing two identical Objects 2

Status
Not open for further replies.

Watts

Programmer
Jan 18, 2001
80
US
I have two identical object with both private and public members. I want to compare the two without having to traverse through all of the member one at a time. Is there any way to do this without writing my own function?

Example (psuedocode):

Rectangle rect1, rect2;
{some code here}
if(rect1==rect2) then {code}

Keep in mind that the Rectangle object has (x, y, width, height) memebers.
 
if( rect1 == rect2 )
this will compare the objects memory addresses and therefore, even if they contain the same information, if they are two different objects then it will return false.

A way to compare the contents is by using the equals() method. Most classes make the comparison of the information within the object.

e.g. if you had a String containing "Hello" caled str1 and a String called str2 containing "Hello", then by doing '==' upon it will return false. Do str1.equals( str2 ) will return true.
 
if( rect1 == rect2 )
this will compare the objects memory addresses and therefore, even if they contain the same information, if they are two different objects then it will return false.

A way to compare the contents is by using the equals() method. Most classes make the comparison of the information within the object.

e.g. if you had a String containing "Hello" caled str1 and a String called str2 containing "Hello", then by doing '==' upon it will return false. Do str1.equals( str2 ) will return true.

Rectangle should compare the members too.
 
Great I will have to use this, will this also work for User defined classes? If not, do you have to override this function with one of your own I wonder?
 
You are correct, when you write your own classes you need to override equals() to get the desired functionality. If you do not override it then you will be using the version of equals() that is inherited from Object which has the same functionality as ==. Wushutwist
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top