Java HashSet Collection
HashSet Collection
Inherit from Abstractcollection
Implements the Collection interface
The bottom layer uses the HashMap collection to store the elements as keys to the HashMap collection
The iterator invokes the Map.keyset () of the underlying map. iterator
Store unordered, cannot use index to get elements
Element is not repeatable, hash algorithm and Equals method to determine whether the element is repeated, repeat does not add the use method
adding elements
Example
hashset<integer> hs = new hashset<> ();
add Element
Hs.add (a);
Hs.add (a);
System.out.println ("Add (E E):" + HS);
Add a set
//Because the collection itself is added, all elements are duplicated and not added
Hs.addall (HS);
System.out.println ("AddAll" (collection<? Extends e> c): "+ HS";
Run results
removing elements from
Example
hashset<integer> hs = new hashset<> ();
for (int i = 1; I <= 5; i++) {
hs.add (i);
}
Hs.remove (Integer.valueof (3));
System.out.println ("Remove (Object O):" + HS);
Remove intersection element
//RemoveAll (collection<?> C)
Run results
Judge related
Example
hashset<integer> hs = new hashset<> ();
for (int i = 1; I <= 5; i++) {
hs.add (i);
}
Determines whether the collection contains the specified element
boolean result = Hs.contains (integer.valueof (3));
System.out.println ("contains (Object o)" + result);
Determines whether the set is null result
= Hs.isempty ();
System.out.println ("IsEmpty ()" + result);
Operation result
Traverse Collection
Converts the collection to an array, and then iterates through the arrays
Example
hashset<integer> hs = new hashset<> ();
for (int i = 1; I <= 5; i++) {
hs.add (i);
}
integer[] Array = Hs.toarray (new Integer[hs.size ()));
for (int i = 0; i < Array.Length i++) {
System.out.println (array[i]);
Run results
foreach (Enhanced for) sample
hashset<integer> hs = new hashset<> ();
for (int i = 1; I <= 5; i++) {
hs.add (i);
}
integer[] Array = Hs.toarray (new Integer[hs.size ()));
for (int i = 0; i < Array.Length i++) {
System.out.println (array[i]);
foreach (Enhanced for)
Example
hashset<integer> hs = new hashset<> ();
for (int i = 1; I <= 5; i++) {
hs.add (i);
}
for (Integer i:hs) {
System.out.println (i);
}
Run results
Iterator iterator
Example
hashset<integer> hs = new hashset<> ();
for (int i = 1; I <= 5; i++) {
hs.add (i);
}
Iterator<integer> iterator = Hs.iterator ();
while (Iterator.hasnext ()) {
System.out.println (Iterator.next ());
}
Run results