Because they have different references. ==
gives reference equality if two object are referenced by the same reference or not, to compare two object use equals
method instead. like
checks if two object are equal, but you have to override equals
and hashCode
method, to define equality
p1.equals(p2) //
An example Point
class might look like this:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// accessors omitted for brevity
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
EDIT:
For object comparison, the equality ( ==
)operator is applied to the references to the objects, not the objects they point to. Two references are equal if and only if they point to the same object, or both point to null. See the examples below:
Point x = new Point(3,4);
Point y = new Point (3,4);
Point z = x;
System.out.println(x == y); // Outputs false
System.out.println(x.equals(y) ); // Outputs true
System.out.println(x == z); // Outputs true