ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Version {
    int major, minor;
    Version(int ma, int mi) { major = ma; minor = mi; }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Version v)) return false;
        return major == v.major; // BUG: minor ignored
    }
    @Override
    public int hashCode() { return Objects.hash(major, minor); }
}
// in main:
Set<Version> set = new HashSet<>();
set.add(new Version(1, 0));
set.add(new Version(1, 1));
System.out.println(set.size());
  1. A. 1
  2. B. 2
  3. C. 0
  4. D. Non-deterministic

Correct answer: B. 2

hashCode() includes minor, so Version(1,0) and Version(1,1) hash to different buckets even though the buggy equals() (which ignores minor) would consider them equal — because they never land in the same bucket, equals() is never even invoked to compare them, so both get added: size 2, masking the equals bug entirely.

More OOP with C++ and Java questions

Exams that ask this topic