Question 7
Back to Exercise
What is the output of the following Java program?
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!