首页 > 其他 > 详细

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

时间:2014-09-17 20:29:32      阅读:261      评论:0      收藏:0      [点我收藏+]

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程序员都知道,所以需要注意下,以免编程出错。


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

原文:http://blog.csdn.net/aitangyong/article/details/39345297

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!