Set sets ensure that elements are unique
- The underlying data structure of Set collection is hash table
- The only way to do this:
When storing elements in a Set set, a hash value will be generated, which is stored according to different hash values. First, use the haseCode() method to obtain an int type hash value. First, compare whether the hash value is the same. If different, it means that there is no same element in the Set, and store it directly. If the same, then call the equals() method to determine whether the content is completely consistent and different In short, it means:
1) ----hashCode()
Different: storage
2) --- same: equals ()
Different: storage
Same: no storage - Using the hashCode () method to compare the hash value first rather than using equals () directly improves the comparison efficiency
- hashCode() and equals() bottom source code:
public int hashCode() { int h = 0; Iterator<E> i = iterator(); while (i.hasNext()) { E obj = i.next(); if (obj != null) h += obj.hashCode(); } return h; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection<?> c = (Collection<?>) o; if (c.size() != size()) return false; try { return containsAll(c); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } }
- Set collection stores custom objects
(1) The equals and hashCode methods are not overridden
import java.util.HashSet; import java.util.Set; public class SetTest { public static void main(String[] args) { Set<Person> set=new HashSet<>(); set.add(new Person("Jia Baoyu",18)); set.add(new Person("Lin Daiyu",16)); set.add(new Person("Xue Bao Chai",20)); set.add(new Person("Lin Daiyu",16)); set.add(new Person("Lin Daiyu",17)); System.out.println("No rewrite equals and hashCode Method"); for (Person person : set) { System.out.println(person); } } }
Result:
It is not unique not to override the equals and hashCode method storage elements
(2) Override equals and hashCode methods in custom classes
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); }
Operation result:
To store a custom object, you need to override the above two methods by yourself, and only when the content is completely different will it not be stored repeatedly.