Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this java equals() method violates the symmetric implementation rule?

Tags:

java

Following code is a wrong implementation of java equals method. It violated the symmetric rule. But I do not know how it violated this rule. Please point it out where in this method it violated the symmetric rule.

public class WrongEquals {

    private final String variable;

    public WrongEquals(String variable) {
            this.variable = variable;
    }

    @override public boolean equals(Object o) {
            if (this == o) {
                    return true;
            }
            if (o instanceof String) {
                    return variable.equals((String) o);
            }
            if (o instanceof WrongEquals) {
                    return variable.equals(((WrongEquals) o).variable);
            }
            return false;
    }

    @override
            public int hashCode() {
                    return (variable == null ? 0 : variable.hashCode());
            }
}
like image 956
loop Avatar asked Nov 05 '25 11:11

loop


2 Answers

Because your WrongEquals instance can be equal to some String, but no String will be equal to any instance of WrongEquals

Look at the String implementation of equals() (as of JDK 7)

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String) anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                        return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

Obviously this implementation ensures that any equality will only exist between another String instance.

like image 169
Kon Avatar answered Nov 08 '25 10:11

Kon


(This is just an extension and illustration of Kon's prior answer)

Try adding this main program:

  public static void main(String[] args){
    WrongEquals a = new WrongEquals("xyzzy");
    String b = "xyzzy";
    System.out.println(a.equals(b));
    System.out.println(b.equals(a));
  }

It will display:

true
false
like image 27
Patricia Shanahan Avatar answered Nov 08 '25 10:11

Patricia Shanahan