Challenge: Equal Points
Completed
Write a class Point with x and y and override equals (and hashCode) so points with the same coordinates are equal. Read two points and print same if they are equal, otherwise different.
Input
Four whole numbers: x1 y1 x2 y2.
Output
same or different.
Example
Input
1 2 1 2
Output
same
Editor
Java
Hints
The parameter of equals must be Object, not Point.
Use instanceof, then cast to Point.
Solution explanation
With the parameter type Object our method really overrides Object.equals, so it's used everywhere Java compares objects.
Show solution
import java.util.Objects;
import java.util.Scanner;
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Point a = new Point(sc.nextInt(), sc.nextInt());
Point b = new Point(sc.nextInt(), sc.nextInt());
System.out.println(a.equals(b) ? "same" : "different");
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module