Collection, Iterator, Set, HashSet, iteratorhashset
Basic Methods of the Collection Interface
|
Boolean add (Object o) |
Add an object to the set |
|
Void clear () |
Delete all objects in the Set |
|
Boolean isEmpty () |
Determines whether the set is empty. |
|
Remove (Object o) |
Deletes an object reference from a collection. |
|
Int size () |
Returns the number of elements in a collection. |
The Set interface inherits the preceding methods of the Collection interface. The HashSet class implements the Set interface.
Import java. util. set; import java. util. hashSet; class Test {public static void main (String args []) {Set <String> hs = new HashSet <String> (); System. out. println (hs. isEmpty (); // determines whether the hs is empty. add ("a"); hs. add ("B"); hs. add ("c"); hs. add ("d"); hs. add ("c"); // repeat cSystem. out. println ("hs object length is" + hs. size (); hs. remove ("d"); // remove dSystem. out. println ("removed" + hs. size (); hs. clear (); // clear System. out. println ("after clear" + hs. size ());}}
Objects in the List can be read by subscript. However, because the objects in the Set are not sorted in a specific order, the data in the Set cannot be read using the following method, we use the Iterator to traverse the data in the Set.
Set is the sub-interface of Collection, and Collection is the sub-interface of Iterator. Commonly used methods of the Itreator interface include hasNext () and next (). The iterator model is as follows:
Arrows represent cursors, and boxes represent objects. When the iterator object calls the hasNext () method, the return value is a Boolean value. If there is any next object after the cursor is determined, true is returned. When next () is called, The next object referred to by the cursor is returned, and the cursor moves one bit backward.
Import java. util. set; import java. util. hashSet; import java. util. iterator; class Test {public static void main (String args []) {Set <String> hs = new HashSet <String> (); hs. add ("B"); hs. add ("d"); hs. add ("a"); hs. add ("c"); // call the iterator method of the Collection interface to generate the iterator object itIterator <String> it = hs. iterator (); while (it. hasNext () {System. out. println (it. next ());}}}