Bob
Bob

Reputation: 10805

Java compare string with hash and without hash

I have a String that contains hash (it was automatically generated by third party program) and I have another String that do not contain hash and I need to compare to the first String.

Method .equals() give false. How else I can compare them?

Upvotes: 0

Views: 765

Answers (3)

Rebecca Abriam
Rebecca Abriam

Reputation: 560

If I understood it correctly, there are two String to compare, one is the original String (s1) and the second String which contains the original String + its hash (s2) inserted by a 3rd party program. If so, the built-in equals() method will not return true. I would be creating my own implementation of equals() method to check this.

These two methods should do the trick, but I prefer the second one.

private static boolean equals(String s1, String s2) {
    String s1Hash = String.valueOf(s1.hashCode());
    return (s2.contains(s1) && s2.contains(s1Hash));
}

private static boolean equals2(String s1, String s2) {
    String s1Hash = String.valueOf(s1.hashCode());
    String s2NoHash = s2.replace(s1Hash,"");
    return (s1.equals(s2NoHash));
}

Hope this answers what you are looking for. Otherwise, a concrete example to describe the problem will be good.

Upvotes: 0

Keerthivasan
Keerthivasan

Reputation: 12880

If Methods == and .equals() give false, then both the String references are not pointing to neither the same object and nor meaningfully equivalent objects in heap. Adding to that, == should not be used to compare String literals

Upvotes: 2

f1sh
f1sh

Reputation: 11934

String values are compared using equals(String anotherString). If that method returns false, the string values are simply not equal.

Check your strings for uppercase vs. lowercase, leading and trailing spaces and so on.

Upvotes: 0

Related Questions