Map.Entry的由来和使用

首先,回忆和练习一下HashMap的遍历
package Exercise.exercise;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Demo01 {
    public static void main(String[] args) {
        HashMap<String,String> hm=new
                HashMap<>();

        hm.put("赵又廷","高圆圆");
        hm.put("邓超","孙俪");
        hm.put("刘恺威","杨幂");

        Set<String> set=hm.keySet();

//        //调用keySet方法:set中存储的是所有的key
//        Iterator<String> it=set.iterator();
//
//        //取出set中所有的key,根据key来获取对应的value
//        while (it.hasNext()){
//           String key=it.next();
//           String value=hm.get(key);
//           System.out.println(key+" "+value);
//        }
//

        for (String key:set){
            String value=hm.get(key);
            System.out.println(key+" "+value);
        }
    }
}

package
test01.Map.Entry; /** * public interface Map<k,v>{ //Map外部接口 * interface Entry<k,v>{ //Entry上的k,v随着Map上 * //k,v变化 * K getKey(); * V getValue(); //定义的两个抽象方法 * } * } * class A implements Map.Entry<k,v>{ * K key; * V value; * * //重写方法 * public final K getKey(){ * return key; * } * public final V getValue(){ * return value; * } * //结论:Map.Entry中封装了key,value,并且封装了 * //获取key和value方法(getKey,getValue); * * //这个结论是通过分析源码得到的; * } * */ public class Demo02 { public static void main(String[] args){
Map<String,String> hm=new HashMap<String,String>();
hm.put("邓超","孙俪");
        hm.put("赵又廷","高圆圆");
        hm.put("刘恺威","杨幂");
//利用entrySet来遍历
Set<Map.Entry<String,String>> set=hm.entrySet();
//迭代器方式遍历
/**
Iterator<Map.Entry<String,String>> me=it.next();
while(){
Map.Entry<String,String> me=it.next();
String key=me.getKey();
String value=me.getValue();
System.out.println(key+" "+value);
}
*/
//增强for来遍历
for(Map.Entry<String,String> me:set){
           String key=me.getKey();
String value=me.getValue();
System.out.println(key+" "+value);
         }
     }
}

 说明:之所以用这样,是因为set可以直接用迭代器的方式,而Map这个不能直接用迭代器,因为set/list的父接口是Collection  ,而最后的根是Iterator,而Map不具备这个,所以要

打包到Set中,EntrySet这个接口对象类似,它是Map接口的接口,即内部接口,这个和内部类类似,自己多默写,多总结,多练习,熟能生巧;

posted @ 2019-06-30 23:54  贰零一八  阅读(209)  评论(0编辑  收藏  举报