HashMap遍历

package  cn.yu.hashmap;

import  java.util.HashMap;
import  java.util.Iterator;
import  java.util.Map;
import  java.util.Map.Entry;

public   class  hashmap {
     public   static   void  main(String[] args) {
        HashMap < String, String >  map  =   new  HashMap < String, String > ();
        map.put( " 1 " ,  " aaa " );
        map.put( " 2 " ,  " bbb " );
        map.put( " 3 " ,  " ccc " );
        map.put( " 4 " ,  " ddd " );
        map.put( " 5 " ,  " eee " );
        map.put( " 6 " ,  " fff " );
        map.put( " 7 " ,  " ggg " );
        map.put( " 8 " ,  " hhh " );
        map.put( " 9 " ,  " iii " );

         /*
         * 遍历hashmap
          */
        hashmap1(map);
        line();
         /*
         * 用keySet遍历
          */
        hashmap2(map);
        line();
         /*
         * 用entrySet遍历 速度快
          */
        hashmap3(map);
        line();
    }

     public   static   void  hashmap1(HashMap < String, String >  map) {
         for  (Map.Entry < String, String >  entry : map.entrySet()) {
            System.out.println( " Key: "   +  entry.getKey()  +   "    value: "   +  entry.getValue().toString());
        }

    }

     public   static   void  hashmap2(HashMap < String, String >  map) {
        Iterator < String >  it = map.keySet().iterator(); // 这是取得键对象   
         while (it.hasNext())   {   
           System.out.println( " value:  " + map.get(it.next()));    // 获得键所对应的值。   
        } 
    }

     public   static   void  hashmap3(HashMap < String, String >  map) {
        Iterator < Entry < String, String >>  it  =  map.entrySet().iterator();  
         while (it.hasNext()){  
            Entry < String, String >   entry = (Entry < String, String > )it.next();  
            System.out.println( " key: " + entry.getKey() + "    value: " + entry.getValue());
            
        }  
    }
     public   static   void  line(){
        System.out.println( " ========================华丽的分割线=============================== " );
    }
}



  Hashmap实际上是一个数组和链表的结合体,利用数组来模拟一个个桶(类似于Bucket Sort)以快速存取不同hashCode的key,对于相同hashCode的不同key,再调用其equals方法从List中提取出和key所相对应的value

转载于:https://www.cnblogs.com/harrygogo/p/3526642.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值