• 使用HashMap须要注意的事儿:不要暴露Map.entry给外部不可信代码Map.entrySet()


    Map/HashMap是java中一种非经常常使用的数据结构,一般我们在应用中做的事情就是调用put向容器写入数据或者是get从容器读取数据。

    Map.entrySet()这种方法返回了键值对的集合,也是JDK官方推荐的遍历Map的方式。

    Set<Map.Entry<String, String>> allEntrys = maps.entrySet();
    
    for (Map.Entry<String, String> as : allEntrys)
    {
        String key = as.getKey();
    	String value = as.getValue();
    }


    可是我们不应该将Map.entrySet()的返回结果,传递给不可信代码。为什么呢?先看以下一段代码:

     public static void main(String[] args) throws Exception
     {
         HashMap<String, String> maps = new HashMap<String, String>();
         maps.put("name", "xiu");
         maps.put("age", "25");
         
         System.out.println(maps);// {age=25, name=xiu}
    	 
         Set<Map.Entry<String, String>> allEntrys = maps.entrySet();
         Map.Entry<String, String> nameEntry = null;
         for (Map.Entry<String, String> as : allEntrys)
         {
             String key = as.getKey();
             if (key.equals("name"))
             {
                 nameEntry = as;
             }
         }
         // 删除entry
         allEntrys.remove(nameEntry);
         
         System.out.println(maps);// {age=25}
     }
    非常明显,我们通过Map.entrySet()的返回结果,可以删除原始HashMap中存储的键值对。假设我们将Set<Map.Entry<String, String>> allEntrys 作为函数參数传递给不可信代码。那么外部的恶意代码就能删除原始HashMap中存储的数据。所以我们应该避免传递Set<Map.Entry<String, String>>作为函数參数。防止外部代码恶意的或者不小心改动了原始的数据。

    这个隐藏的功能不是全部的java程序猿都知道,所以须要注意下,以免编程出错。


  • 相关阅读:
    新数学丛书《连分数》 习题 1.1
    连分数中一个有意思的小玩意儿
    无聊博文之:用同余的语言阐述欧几里德算法
    有向无环图
    Codeforces Round #658 (Div. 2)
    常用代码模板3——搜索与图论
    什么是动态规划?动态规划的意义是什么?(转自知乎)
    Codeforce:4C. Registration system (映射)
    C++与正则表达式入门
    常用代码模板4——数学知识
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5165901.html
Copyright © 2020-2023  润新知