首页 > 其他 > 详细

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

时间:2016-01-28 13:44:21      阅读:232      评论: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://www.cnblogs.com/bhlsheji/p/5165901.html

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