Java-Object Comparison

class ObjectComparison {
    public static void main(String[] args) {
        String s1 = new String("Hello");
        String s2 = new String("Hello");

        System.out.println("[Ref. Comparison]s1" +
            ((s1 == s2) ? " is " : " is not ") +
            "equal to s2."); /*(s1==s2) always return false since the references are compared here*/

        System.out.println("[Value Comparison]s1" +
            ((s1.equals(s2)) ? " is " : " is not ") +
            "equal to s2."); /*(s1.equals(s2)) always return true since the values are compared here*/
    }
}

—Overriding hashCode() in Rectangle—

public int hashCode() {
    String hashStr = "L" + length + "B" + breadth;
    return hashStr.hashCode();
}
  • class String has overridden the hashCode() in Object.
    Implicitly created String object String str = “hello”; are stored in the string constant pool. Hence same valued String objects created implicitly have the same reference (and hence same hash code)- to impart optimization.
  • Implicit creation of object: String str = “hello”;
  • Explicit creation of object: String str = new String(“hello”);
  • class Rectangle makes use of hashCode() in the class String to mimic this behavior.
  • L and B are used as delimiters since Rectangle (11, 20) and Rectangle (1, 120) may have same hash code otherwise.

—Overriding hashCode() in Container—

public int hashCode() {
    String hashStr = "L" + getLength() + "B" + getBreadth() + “H” + height;
    return hashStr.hashCode();
}

—Overriding equals() in Rectangle—

public boolean equals(Object object) {
    boolean equals = false;

    if (object instanceof Rectangle && 
       ((Rectangle) object).getLength() == length &&
       ((Rectangle) object).getBreadth() == breadth) {
        equals = true;
    }

    return equals;
}

—Overriding equals() in Container—

public boolean equals (Object object) {
    boolean equals = false;

    if (object instanceof Container &&
       ((Container) object).getLength() == getLength() &&
       ((Container) object).getBreadth() == getBreadth()&&
       ((Container) object).getHeight() == height) {
        equals = true;
    }

    return equals;
}