#411 Mistakes with HashSet and equals

Companies:
Vadarod
Themes:
JavaCollections & GenericsCode Review

What will be printed?

public class ExerciseOne {

    static class Person {
        int index;
        String name;

        public Person(int index, String name) {
            this.index = index;
            this.name = name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Person person = (Person) o;
            return Objects.equals(name, person.name);
        }
    }

    public static void main(String[] args) {
        Set set = new HashMap<>();
        set.add(new Person(1, "Petr"));
        set.add(new Person(1, "Petr"));
        set.add(new Person(2, "Meshe"));
        set.add(new Person(3, "Ivan"));

        System.out.println(set.size());
    }
}

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