#411 Mistakes with HashSet and equals
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor