Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.Collection;
- import java.util.HashSet;
- import java.util.Objects;
- public class Main {
- public static void main(String[] args) {
- Collection<Person> set = new HashSet<Person>();
- set.add(new Person("Thijs"));
- System.out.println(set.contains(new Person("Thijs")));
- System.out.println(set.contains(new Person("Bob")));
- // Output:
- // EQUALS!
- // true
- // false
- // Note that Object::equals is not called in HashSet::contains if the Object::hashCode of the object doesn't
- // fall in any Hash "buckets" already in the collection, it will assume the collection does not contain the
- // object. It only uses equals to see if colliding hashCodes are from the same object, or just an accidental
- // collision.
- }
- }
- class Person {
- private String name;
- public Person(String name) {
- this.name = name;
- }
- @Override
- public boolean equals(Object o) {
- System.out.println("EQUALS!");
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Person person = (Person) o;
- return Objects.equals(name, person.name);
- }
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement