LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 7

An overridden equals with HashSet Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Emp {
    int id;
    Emp(int id) { this.id = id; }
    @Override public boolean equals(Object o) { return o instanceof Emp e && e.id == id; }
}

class GoodEmp extends Emp {
    GoodEmp(int id) { super(id); }
    @Override public int hashCode() { return Objects.hash(id); }
}

public class Main {
    public static void main(String[] args) {
        Set<Emp> bad = new HashSet<>();
        bad.add(new Emp(1)); bad.add(new Emp(1));
        Set<Emp> good = new HashSet<>();
        good.add(new GoodEmp(1)); good.add(new GoodEmp(1));
        System.out.println(bad.size() + " " + good.size() + " " + new Emp(1).equals(new Emp(1)));
    }
}
  • A 2 1 true Correct
  • B 1 1 true
  • C 2 2 true
  • D 1 2 false
Correct Answer: Option A

Without hashCode, equal Emps land in different buckets, so HashSet keeps both. With a matching hashCode the duplicate is detected.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links