#288 Mutable Object in a HashSet

Companies:
Zolotaya Korona
Themes:
JavaCollections & GenericsCode Review

What will be printed? Explain every output line:

class MyHashSet {
    public static void main(String[] args) {
        MyObject obj = new MyObject(10);
        Set<MyObject> set = new HashSet<MyObject>();
        set.add(obj);
        obj.set(1000);

        System.out.println(set.contains(obj));
        System.out.println(set.contains(new MyObject(10)));
        System.out.println(set.contains(new MyObject(1000)));
        System.out.println(Object.equals(new MyObject(1000), obj));
    }
}

class MyObject {
    private int i;

    private MyObject(int i) {
        set(i);
    }

    private void set(int i) {
        this.i = i;
    }

    public int hashCode() {
        return i;
    }

    public boolean equals(MyObject o) {
        return (o.i == this.i);
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in