zoukankan      html  css  js  c++  java
  • 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接口的接口,即内部接口,这个和内部类类似,自己多默写,多总结,多练习,熟能生巧;

    成年人的世界没有那么多的童话,也没有那么多的逆袭。
  • 相关阅读:
    数据库基本概念(一)
    Java语言概述
    Linx
    小菜鸟之Cisco
    小菜鸟之网络基础1
    小菜鸟之JAVA输入输出
    小菜鸟之java JDBC编程
    小菜鸟之JAVA面试题库1
    小菜鸟之java异常
    小菜鸟之正则表达式
  • 原文地址:https://www.cnblogs.com/shijinglu2018/p/11111850.html
Copyright © 2011-2022 走看看