A Set collection is a collection composed of a series of unordered, non-repeated elements of the same type. When storing data, the hashCode value of its elements must be determined first, and if it is different, it will be stored.
1) Set collection is a subclass of Collection collection.
2) A collection that does not contain duplicate elements.
3) There is no indexed method, so it cannot be traversed with an ordinary for loop.
add(Object element) : Add the specified element to the end of the Set collection.
remove(Object element) : If the specified element exists in the Set collection, remove the element from the Set collection.
clear() : Remove all elements from the Set collection.
isEmpty() : Determine whether there are elements in the Set collection. If it does not return true, it will return false.
contains(Object element) : Determines whether the Set collection contains the specified element, returns true if it does, and returns false if it does not.
iterator() : Returns an iterator (Iterator) object, which is used to traverse the collection.
size() : Returns the number of elements in the Set collection, and the return value is of type int.
For example:
importjava.util.HashSet;importjava.util.Set;publicclassMain{publicstaticvoidmain(String[]args){Setset=newHashSet();Stringb=B;//Add elements to the set set.add(A);set.add( b);set.add(C);set.add(b);set.add(D);set.add(b);set.add(E);//Print the number of set elements System.out.println (set size=+set.size());//Print the set System.out.println(set);//Remove the first "B" element in the set set.remove(b);//Determine whether the set is Contains the "B" element System.out.println (whether it contains B: +set.contains(b)); // Determine whether the set is empty System.out.println (the set set is empty: +set.isEmpty( ));//Clear the collection set.clear();System.out.println(set);}}
The running results are as follows:
Whether the set size=5[A,b,C,D,E] contains B: falseset The set is empty: false[]
The hash value is the value of the int class calculated by JDK based on the address or number of the u-th item. There is a way to obtain the hash value in the Object class, public int hashCode(); returns the hash value.
The characteristics of object hash values are as follows:
1) The hash value returned by the hashCode() method is the same when called multiple times on the same object.
2) By default, the hash values of different objects are different, but you can make the hash values the same by overriding the hashCode method.
Note : Different strings have the same hash value, because String overrides the hashCode method, such as "Chongdi" and "Call", the hash values are both 1179395.