Question discussion

What is the output of the following Java program?import java.util.*; public class Main { static class P { int x; P(int x) { this.x = x; } p…

2521Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

import java.util.*;
public class Main {
    static class P {
        int x;
        P(int x) { this.x = x; }
        public boolean equals(Object o) { return o instanceof P && ((P) o).x == x; }
    }
    public static void main(String[] args) {
        Set<P> s = new HashSet<>();
        s.add(new P(1));
        s.add(new P(1));
        System.out.println(s.size() + " " + new P(1).equals(new P(1)));
    }
}
  • A1 true
  • B2 true
  • C2 false
  • D1 false
Correct answer: B

Explanation

The two objects are equal according to equals(), but hashCode() is not overridden, so they normally get different identity hash codes, go to different buckets and both stay in the HashSet; equal objects must have equal hash codes.

Discussion 0

Nobody has replied yet. Start the discussion!