Search code examples
javalinecoordinatesequalspoint

equals() method to check X and Y coordinates


Ok guys, first off sorry if this code is messy and if my equals() is completely wrong, but this is my first time using it.

I'm trying to create an equals method to check if two lines are equal, two lines are defined as equal if two end points are the same.

My first question is, am i even close with the method in the Point class, and also how would I call the equals() method in the Point class from the Line class?

Thanks for any and all help.

public class Point {

private int x;
private int y;

public Point( int x, int y) {
    this.x = x;
    this.y = y;
}

public int getX() {
    return x;
}
public int getY() {
    return y;
}

public String toString() {
    return "x=" + x + ", y=" + y;
}

public boolean equals(Object o) {
      if (!(o instanceof Point)) {
            return false;
        }
        return (x == ((Point) o).x && y == ((Point) o).y);
}
}

}

for the return this.y, it says "unreachable code". Also Should my Object be "Point" or "Line"?

public class Line {
private Point beg, end;
Color color;

public Line(Point beg, Point end, String color) {
    this.beg = beg;
    this.end = end;


public Point getEnd() {
    return end;
}

public Point getBeg() {
    return beg;
}

public Color getColor() {
    return color;
}

public String toString() {
    return "Beg=" + beg + ", End=" + end + ", Color" + color.toString();
}

Line() {
    return this.beg.equals(Point.x);
    return this.end.equals(Point.y);
}

}

I updated the equals() in point class but I'm still having trouble calling it from the Line class, would it be a similar fix?

Thanks for all the help.


Solution

  • It is unreachable code because you exited the method just before by returning from it . You probably meant this.x == ((Point)o).x && this.y == ((Point)o).y.

    You should have something like:

    @Override
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }
        if (!(o instanceof Point)) {
            return false;
        }
        return (x == ((Point) o).x && y == ((Point) o).y);
    }
    

    Also, for the Line class you compare the relevant fields (beg and end).

    @Override
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }
        if (!(o instanceof Line)) {
            return false;
        }
        return (beg == ((Line) o).beg && end == ((Line) o).end);
    }
    

    When you override equals (and hashCode, always write them in pairs) it is a good idea to use the @Override annotation, in case you write public boolean equals(Point o) (notice the parameter is Point, not Object) by mistake, so the compiler will catch it.