Check if two objects are structurally equal?

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

Now I want to check if these two objects are structurally equal. Does Java offer a tool to compare these objects?

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

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

edit:

class test{ public int a } test t = new test(); ta = 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.

+2
source share
3 answers

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 peers, you should always always override the hashCode method. Please read this link for why: Why always override hashcode () when overriding equals ()?

+5
source

It looks like you can compare with the overridden equals method, which I think ...

+2
source

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(); } } 
+2
source

All Articles