This is the 19th day of my participation in the Genwen Challenge

The Set collection

Before we talk about the HashSet Set, let’s review the Set Set. Set is an interface to Collection. Sets are not allowed to contain the same elements, and sets generally cannot remember the order in which elements were added.

HashSet class

HashSet is a typical implementation of the Set interface. A HashSet uses a Hash algorithm (implemented as a HashMap) to store the elements of a collection, so it has good access and lookup performance.

HashSet has the following characteristics:

1. It does not guarantee the iteration order of collections 2. This class allows null elements 3. This implementation is not synchronous. If multiple threads simultaneously access a hash set and at least one thread modifies the set, synchronization must be performed externally.Copy the code

When you add an object to a HashSet, the HashSet calls the object’s hashCode() method, which returns a decimal integer randomly given by the system. (is the logical address value simulated by the object, not the physical address value stored in the data). HashSet Determines where the object is stored in the HashSet based on the hashCode value.

A HashSet determines whether two elements are equal by comparing them through equals and the hashCode values of the two objects are also equal.

Let’s look at a concrete example:

import java.util.HashSet; public class TestHashSet { public static void main(String[] args) { A a1 = new A(); A a2 = new A(); B b1 = new B(); B b2 = new B(); C c1 = new C(); C c2 = new C(); HashSet hashSet = new HashSet<String>(); System.out.println(hashSet.add(a1)); System.out.println(hashSet.add(a2)); System.out.println(hashSet.add(b1)); System.out.println(hashSet.add(b2)); System.out.println(hashSet.add(c1)); System.out.println(hashSet.add(c2)); Class A{@override public Boolean equals(Object o){return true; Class B{@override public int hashCode(){return 1; }} /** * Class C's equals method always returns true, and the hashCode method always returns 2; */ class C{ @Override public boolean equals(Object o){ return true; } @Override public int hashCode(){ return 2; }}Copy the code

It should be noted from the result that putting an object into a HashSet should also override the hashCode method after overriding equals. Otherwise, conflicts may result. Try to ensure that the hashCode method returns the same value when overridden equals returns true.

For the methods in the HashSet class, you can refer to the Java API documentation. The purpose of this article is to give you an overview of hashsets and some of the important features of hsahsets.