Several Methods to Traverse Key and value in hashtable

Source: Internet
Author: User
Several Methods to Traverse Key and value in hashtable

 

[Java]View plaincopy
  1. Package corejava;
  2. Import java. util. enumeration;
  3. Import java. util. hashtable;
  4. Import java. util. iterator;
  5. /*
  6. * Processing Principle: extract the key first and then use the key to obtain the value.
  7. */
  8. Public class hashtabledemo {
  9. Public static void main (string [] ARGs ){
  10. Hashtable <string, string> ht = new hashtable <string, string> ();
  11. For (INT I = 0; I <10; I ++ ){
  12. Ht. Put ("key" + I, "value" + I );
  13. }
  14. // Cyclically Traverse Key and Value
  15. For (iterator <string> itr = HT. keyset (). iterator (); itr. hasnext ();){
  16. String key = (string) itr. Next ();
  17. String value = (string) Ht. Get (key );
  18. System. Out. println (Key + "(for)" + value );
  19. }
  20. // Cyclically Traverse Key and Value
  21. Iterator <string> itr = HT. keyset (). iterator ();
  22. While (itr. hasnext ()){
  23. String STR = (string) itr. Next ();
  24. System. Out. println (STR + "(while)" + Ht. Get (STR ));
  25. }
  26. // Obtain value using Enumeration
  27. Enumeration <string> E = HT. Elements ();
  28. While (E. hasmoreelements ()){
  29. System. Out. println (E. nextelement ());
  30. }
  31. // Obtain the key: Value Pair using Enumeration
  32. Enumeration <string> E2 = Ht. Keys ();
  33. While (e2.hasmoreelements ()){
  34. String key = e2.nextelement ();
  35. System. Out. println (Key + "=" + Ht. Get (key ));
  36. }
  37. }
  38. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.