Several Methods to Traverse Key and value in hashtable
[Java]View plaincopy
- Package corejava;
- Import java. util. enumeration;
- Import java. util. hashtable;
- Import java. util. iterator;
- /*
- * Processing Principle: extract the key first and then use the key to obtain the value.
- */
- Public class hashtabledemo {
- Public static void main (string [] ARGs ){
- Hashtable <string, string> ht = new hashtable <string, string> ();
- For (INT I = 0; I <10; I ++ ){
- Ht. Put ("key" + I, "value" + I );
- }
- // Cyclically Traverse Key and Value
- For (iterator <string> itr = HT. keyset (). iterator (); itr. hasnext ();){
- String key = (string) itr. Next ();
- String value = (string) Ht. Get (key );
- System. Out. println (Key + "(for)" + value );
- }
- // Cyclically Traverse Key and Value
- Iterator <string> itr = HT. keyset (). iterator ();
- While (itr. hasnext ()){
- String STR = (string) itr. Next ();
- System. Out. println (STR + "(while)" + Ht. Get (STR ));
- }
- // Obtain value using Enumeration
- Enumeration <string> E = HT. Elements ();
- While (E. hasmoreelements ()){
- System. Out. println (E. nextelement ());
- }
- // Obtain the key: Value Pair using Enumeration
- Enumeration <string> E2 = Ht. Keys ();
- While (e2.hasmoreelements ()){
- String key = e2.nextelement ();
- System. Out. println (Key + "=" + Ht. Get (key ));
- }
- }
- }