Reputation: 30588
For example, I have two object, which a the class, Person.
Person A:
User_name:n1
Password:1234
Email:[email protected]
Person B:
User_name:n1
Password:1234
Email:[email protected]
Because both Person A and Person B have same values, so, I would like to write my own isValueEqual function. first, I want to compare their classes, then, I campare their value one by one to check whether it is equal. I think this way is super time consuming. So, I think is this reliable to make it become a JSON string, and use the md5 to hash them, and compare the hash only. So, is this a better approach for comparing their value? Thanks.
Upvotes: 2
Views: 3276
Reputation: 691785
To explain what Jim Garrison explains in this comment in more details, just consider the work necessary to implement equals by comparing the fields, and the work necessary to implement it by generating a hash and comparing the hashes. Let's take your example, with A and B differing only by the last letter of their email (which is the worst case).
First method:
Second method:
Note that if the persons differ by the first character or the length of their name, the first method stops immediately, whereas the second one must do every step.
Upvotes: 2
Reputation: 199234
Something like this is way faster than converting the object to JSON and then computing its MD5
public boolean equals( Object o ) {
Person p = null;
return o instanceof Person
&& this.name.equals((p = (Person) o).name)
&& this.password.equals(p.password)
&& this.email.equals(p.email);
}
But, don't believe me, measure.
Upvotes: 0
Reputation: 2921
Hash function gives you false positive, so you are likely to hit false matching eventually.
Though if your objects are not going to exhaust MD5 and false matching does not bother you then surely you can go for MD5.
Upvotes: 0
Reputation: 272307
No. You can encounter a hash collision and thus identify two different objects as being the same.
What's time consuming about comparing the fields ? If you're worried about compute time, measure it first (I would be very surprised if you think it's too slow, and a hash computation will be massively slower). If you're worried about implementation time, check out Apache Commons EqualsBuilder or similar.
Upvotes: 5