Advertisement
tvdhout

HashSet::contains using .equals()

May 9th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Objects;
  6.  
  7. public class Main {
  8.  
  9.     public static void main(String[] args) {
  10.         Collection<Person> set = new HashSet<Person>();
  11.  
  12.         set.add(new Person("Thijs"));
  13.         System.out.println(set.contains(new Person("Thijs")));
  14.         System.out.println(set.contains(new Person("Bob")));
  15.  
  16.         // Output:
  17.         // EQUALS!
  18.         // true
  19.         // false
  20.  
  21.         // Note that Object::equals is not called in HashSet::contains if the Object::hashCode of the object doesn't
  22.         // fall in any Hash "buckets" already in the collection, it will assume the collection does not contain the
  23.         // object. It only uses equals to see if colliding hashCodes are from the same object, or just an accidental
  24.         // collision.
  25.     }
  26. }
  27.  
  28. class Person {
  29.     private String name;
  30.     public Person(String name) {
  31.         this.name = name;
  32.     }
  33.  
  34.     @Override
  35.     public boolean equals(Object o) {
  36.         System.out.println("EQUALS!");
  37.         if (this == o) return true;
  38.         if (o == null || getClass() != o.getClass()) return false;
  39.         Person person = (Person) o;
  40.         return Objects.equals(name, person.name);
  41.     }
  42.  
  43.     @Override
  44.     public int hashCode() {
  45.         return Objects.hash(name);
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement