014-008-012

Overriding equals() and hashCode()

Medium

Problem Description

Overriding equals() and hashCode()

In this problem: You will override the equals() and hashCode() methods from the Object class in a Point class to enable value-based comparison of coordinate points.

Learning Objective: Understand how to correctly override equals() and hashCode(), and the relationship between them

Overview

The default equals() compares object references (addresses). For coordinate points, we want to consider two points equal if their x and y coordinates are the same, so we override equals(). When overriding equals(), you must also override hashCode().

Specifications

  • Point class: x (int), y (int) fields, constructor, getters
  • equals(Object obj): returns true if x and y coordinates are equal
  • hashCode(): computes hash value based on x and y coordinates
  • Compare two Point objects and print the results

Output Format

Point(3, 5)
Point(3, 5)
Equals: true
Hash match: true

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up