What is the logic behind ==
returning false when two reference variables are referring to same Object having same hash code values?
public class One {
public static void main(String[] args) {
One o = new One();
One o1 = o;
System.out.println(o.toString());
System.out.println(o1.toString());
System.out.println(o.hashCode());
System.out.println(o1.hashCode());
// Why does it print false ?
System.out.println(o.toString()==o1.toString()); // false
System.out.println(o.hashCode()==o1.hashCode()); // true
System.out.println(o.equals(o1)); // true
System.out.println(o.toString().hashCode()==o.toString().hashCode()); // true
}
}
The line with
has a
toString()
. EachtoString()
creates a new String Object, which are different Objects that have their own memory locations. So the==
actually checks the memory addresses between those new String Objects.Always compare strings with
String#equals
, not with==
.