Defining a Coordinate class

exercise No. 191

Representing integer coordinate values

Q:

Implement a class Coordinate to represent integer Cartesian coordinate values:

public class Coordinate {

  private int x, y;
  ...
}

Provide an appropriate constructor and override both toString() and equals() to allow execution of:

// Defining and testing integer coordinates
final Coordinate
  c12 = new Coordinate(1, 2),
  c52 = new Coordinate(5, 0),
  c12Duplicate = new Coordinate(1, 2);


System.out.println("c12:"+ c12);
System.out.println("c12.equals(c52):"+ c12.equals(c52));
System.out.println("c12.equals(c12Duplicate):"+ c12.equals(c12Duplicate));
System.out.println("c12.equals(\"dummy\"):"+ c12.equals("dummy"));

System.out.println(c12);

This should yield the expected output:

c12:(1|2)
c12.equals(c52):false
c12.equals(c12Duplicate):true
c12.equals("dummy"):false
(1|2)

A:

public class Coordinate {

  private int x, y;

  /**
   * Create a Cartesian coordinate / point.
   * @param x
   * @param y
   */
  public Coordinate(int x, int y) {
    this.x = x;
    this.y = y;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Coordinate c) {
      return x == c.x &&
          y == c.y;
    } else {
      return false;
    }
  }

  @Override
  public String toString() {
    return "(" + x + "|" + y + ")";
  }
}