2

I have a company object with different departments and employees. I have successfully serialized my object and loaded it in my program again.

Now I want to test if those two objects are structurally equal. Does java offer me a tool to compare those objects?

I should add that my object has a list filled with other objects.

Or do I have to write my own test for this?

edit:

class test{

public int a

}
test t = new test();
t.a = 1;

test t1 = new test();
t1.a = 1;

now I want to compare t and t1 if they are the same based on their values.

Maik Klein
  • 15,548
  • 27
  • 101
  • 197

3 Answers3

5

You can override the equals method in the Test class as follows:

public boolean equals(Object other) {
    if (other == null) {
       return false;
    }
    if (!(other instanceof Test)) {
       return false;
    }
    return this.a == ((Test) other).a;
}

Also: When overriding equals, you always should also always override the hashCode method. Please see this reference for why: Why always override hashcode() if overriding equals()?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48
2

Sounds like you can compare with overridden equals method I think...

ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54
2

Google Guava provides ComparisonChain:

   public int compareTo(Foo that) {
     return ComparisonChain.start()
         .compare(this.aString, that.aString)
         .compare(this.anInt, that.anInt)
         .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
         .result();
   }

Apache Commons provides CompareToBuilder:

   public int compareTo(Object o) {
     MyClass myClass = (MyClass) o;
     return new CompareToBuilder()
       .appendSuper(super.compareTo(o)
       .append(this.field1, myClass.field1)
       .append(this.field2, myClass.field2)
       .append(this.field3, myClass.field3)
       .toComparison();
   }
 }
Josh Lee
  • 171,072
  • 38
  • 269
  • 275