What is the fastest and most effective way to test Deep Equal for two java objects?

I have two java objects with a byte[] field of the order of millions. What is the fastest and most effective way to test Deep Equal for these Java objects?

Example object:

 @Entity public class NormalBook { @Id private String bookId; @Column private String title; @Column private byte[] pdfFile; //setters and getters } 

Note. I do this for the ORM tool, basically I test the object (which is in a managed state) with the object present in the Persistence Context.

+5
source share
3 answers

Override equals() or have a * helper method (wrong option!) And do it in 5 steps:

 1. Check for *not null*. 2. Check for same *type*. 3. Check for *size of byte[]*. 4. Check for `==` (*reference equality* of byte[]) 5. Start comparing byte values 
+2
source

In the definition of equals() in an object class, use the following:

 java.util.Arrays.equals(bs1, bs2) 

You can also check if they are the same array (instance). Although this method may well do it.

For example (and make some assumptions about your class that contains arrays):

 public boolean equals(Object obj) { if(this == obj) return true; if(!(obj instanceof MyObject)) // covers case where obj null, too. return false; return Arrays.equals(this.bytes, ((MyObject)obj).bytes); } 

If there are other fields in your class, your equals() should consider them as well.

(It might be better to answer the question if you can provide additional information about what data is stored in arrays.)

0
source

If your class has fields like byte[] , you can use something like:

 public class MyClass { byte[] a; public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyClass other = (MyClass) obj; if (!Arrays.equals(a, other.a)) return false; return true; } } 

If you are concerned about performance and can guarantee a unique hascode (this is important the hascode should be unique ), then you can simply compare the hascode.

0
source

All Articles