Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you make a custom object usable as a HashMap key? Custom object को HashMap key की तरह usable कैसे बनाएं?

Answer

To use a custom class as a HashMap key correctly, you must override both hashCode() and equals() consistently - HashMap relies on both to locate and match keys.

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Point)) return false;
        Point other = (Point) obj;
        return this.x == other.x && this.y == other.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);  // must be consistent with equals()
    }
}

Map<Point, String> map = new HashMap<>();
map.put(new Point(1, 2), 'First');

// Even though this is a DIFFERENT object, equals()/hashCode() make it match
System.out.println(map.get(new Point(1, 2)));  // 'First'

// WITHOUT overriding equals()/hashCode() (using default Object identity):
class BadPoint {
    int x, y;
    BadPoint(int x, int y) { this.x = x; this.y = y; }
    // uses default Object.equals() (reference equality) and hashCode()
}
Map<BadPoint, String> badMap = new HashMap<>();
badMap.put(new BadPoint(1, 2), 'First');
System.out.println(badMap.get(new BadPoint(1, 2)));  // null! different object, no match

// GOLDEN RULE: equal objects (per equals()) MUST have equal hashCode()
// values. Violating this breaks HashMap/HashSet lookups silently.

Custom class को HashMap key की तरह सही से use करने के लिए hashCode() और equals() दोनों को consistently override करना ज़रूरी है।

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Point)) return false;
        Point other = (Point) obj;
        return this.x == other.x && this.y == other.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

Map<Point, String> map = new HashMap<>();
map.put(new Point(1, 2), 'First');

System.out.println(map.get(new Point(1, 2)));  // 'First'

// बिना override किए default Object identity use होती है
class BadPoint {
    int x, y;
    BadPoint(int x, int y) { this.x = x; this.y = y; }
}
Map<BadPoint, String> badMap = new HashMap<>();
badMap.put(new BadPoint(1, 2), 'First');
System.out.println(badMap.get(new BadPoint(1, 2)));  // null!

// GOLDEN RULE: equal objects (equals() से) का hashCode() भी equal होना चाहिए

Was this answer clear?