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

时间:2023-07-21 20:07:38

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