Deepak
Deepak

Reputation: 373

Compare 2 objects

In java.. If when we have to compare an object with another object. We compare each field in that object.

Student1 object has marks1, marks2, marks3, name, age as fields. Student2 object has marks1, marks2, marks3, name, age as fields. So to check if 2 students are equal or not... we compare each field.

if(Student1.marks1 == Student2.marks1 && 
   Student1.marks2 == Student2.marks2 && 
   Student1.marks3 == Student2.marks3 && 
   Student1.name == Student2.name && 
   Student1.age == Student2.age)
{
    // we say that Students are same 
}

But what if the Student object has many fields.. Student1 object has marks1, marks2, marks3, name, age, address, color, class, country, section, x, y, z like this 100 such fields Student2 object has marks1, marks2, marks3, name, age, address, color, class, country, section, x, y, z like this 100 such fields

So how should we now check whether 2 objects are equal or not..? going with the above approach.. of checking each individual field does not make sense since they are 100 such fields.

Someone was telling this could be done by serialization in java. Can any one please tell how we can go about it or any other way?

Upvotes: 0

Views: 625

Answers (4)

M Sach
M Sach

Reputation: 34424

I think you are need to understand what equality actually means

Well if you mean that two object are equal (even if they point to different memory location)when their all fields(are equal) then you have to compare all fields. Whether you do it manually or IDE does it for you or third party library, thats the different matter

If you mean that two object are equal only if their point to same memory location, then you can go for == comparison

Upvotes: 0

Keppil
Keppil

Reputation: 46209

If you are willing to use external libraries there is a tool in Apache commons that helps you implement the equals() method using reflection. It is called EqualsBuilder:

Sample usage:

public boolean equals(Object obj) {
   return EqualsBuilder.reflectionEquals(this, obj);
}

Upvotes: 1

Abubakkar
Abubakkar

Reputation: 15644

If you are using an IDE (like Eclipse), then you would not need to worry.

For Eclipse :

  1. Right Click any white area in your code
  2. Click on "Generate equals and hashCode method
  3. Select fields you want in your equals method

This will automatically create your required equals method.

Upvotes: 2

EpicPandaForce
EpicPandaForce

Reputation: 81539

You should use equals() to compare Strings, but most importantly you should just use the generate equals() and hashCode() function in your IDE and see what that generates for you. That's a working, fool-proof and simple solution

Upvotes: 0

Related Questions