Back to questions
JuniorTheoryCommon
What does the program print?
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<P> set = new HashSet<>();
set.add(new P());
set.add(new P());
System.out.println(set.size() + " " + new P().equals(new P()));
}
}
class P { @Override public boolean equals(Object o) { return o instanceof P; } }2 true
- Expecting
1 true: aHashSetcompares hash codes first and callsequalsonly on a match; without ahashCodeoverride they differ, so both objects stay. - Expecting a compile error: Java does not force you to override
hashCodewithequals; breaking the contract compiles and fails quietly at run time.
- What must
hashCodereturn for two objects that are equal byequals? - Can two objects that are not equal have the same hash code?