zoukankan      html  css  js  c++  java
  • 使用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程序猿都知道,所以须要注意下,以免编程出错。


  • 相关阅读:
    IDEA常用快捷指令整理
    Python dict 字典
    内联函数
    【MFC】编辑框 CEdit Ctrl控件自动换行设置
    mysql 多sql文件恢复方案
    Linux: 用64位的系统,能编译32位的程序吗?
    C++ 遍历数组
    工业现场传感器传感器为什么采用电流形式输出?
    【转】电磁阀、电磁铁的工作原理说明
    PCB板强弱电隔离距离不够导致损坏和问题检查记录
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5165901.html
Copyright © 2011-2022 走看看