Set for Java Collection

  • 2020-04-01 01:44:47
  • OfStack

The Set

A collection that does not contain duplicate elements. Specifically, set does not contain e1.equals(e2) elements for e1.e2, and contains at most one null element.

This implementation is not synchronized, if multiple threads access a set at the same time, and at least one thread to modify the set, then it must keep the external synchronization, usually by encapsulating the set to nature of the object to perform synchronization operation to complete, if there is no such object, are: the Collections. SynchronizedSet ();  

HashSet

Set elements without order, do not repeat; The data structure is a hash table;

Principle of ensuring element uniqueness: determine whether the HashCode value of the element is the same, if the same, will continue to determine whether the equals method of the element is true; When an object is stored in a HashSet set, you cannot modify the fields of the object that are involved in calculating the hash value.

TreeSet

You can sort the elements in the Set Set:

(1) to make the element itself Comparable, the element needs to implement the Comparable interface and override the compareTo method, which also becomes the natural order of the elements;

(2) the element itself does not have the comparability, or has the comparability is not required, then the set itself needs to have the comparability. There is a way to compare when the collection is initialized [define the Comparator<> interface, and pass it as an argument to the constructor of the collection]

The following two ways are the two interfaces that TreeSet needs to implement

The class Obj implements Comparable< Obj> {

  Public int compareTo(Obj o)   {

    Return to this.name.com pareTo (o.n ame);  

}}

The class Comptor implements Comparator< ComptorObj> {

  @ Override

  Public int compare(ComptorObj o1, ComptorObj o2) {

    Return to o1.name.com pareTo (o2. Name);

  }}


Related articles: