Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest and efficient way to check Deep Equal for two java objects?

I have got two java objects with byte[] field of the size of the order of millions. What is the fastest and efficient way to check Deep Equal for these java objects?

Sample Entity:

@Entity
public class NormalBook
{

  @Id
  private String bookId;

  @Column
  private String title;

  @Column
  private byte[] pdfFile;

  //setters and getters

  }

Note: I am doing it for an ORM tool basically I am checking an object (which is in managed state) with an object present in Persistence Context.

like image 627
Dev Avatar asked Apr 17 '15 09:04

Dev


People also ask

How do you check if two objects are equal in Java?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.

Why use .equals instead of == Java?

The == operator can't compare conflicting objects, so at that time the compiler surrenders the compile-time error. The equals() method can compare conflicting objects utilizing the equals() method and returns “false”.

How do I compare two fields of objects in Java?

reflect. Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the same name and type.

Can you use == to compare objects in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.


1 Answers

Override equals() or have a *helper method (bad 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 
like image 54
TheLostMind Avatar answered Nov 03 '22 23:11

TheLostMind