如: LinkedCaseInsensitiveMap.put("userId","aa");
caseInsensitiveKeys对象中就会存在一对值:key="userid",value="userId"
LinkedCaseInsensitiveMap实现Map<K,V>接口,putAll(paramMap)方法是是循环遍历paramMap,然后使用put方法插入数据,最终在put方法执行时向caseInsensitiveKeys插入了key值得映射。
源码如下:
@Override public void putAll(Map<? extends String, ? extends V> map) { if (map.isEmpty()) { return; } for (Map.Entry<? extends String, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } }
示例代码:
/**
* 封装查询的两个字段到分别作为map的key和value* @param maps
* @return
*/
private List<Map<String, String>> getMaps(List<Map<String, String>> maps) {
List<Map<String, String>> list = new ArrayList<>();
for (Map<String, String> map:maps){
//LinkedCaseInsensitiveMap这个sping提供的key大小写不敏感的类处理
Map<String, String> tempMap=new LinkedCaseInsensitiveMap<String>();
tempMap.putAll(map);
map=tempMap;
list.add(map);
}
return list;
}
番外篇:
当调用LinkedCaseInsensitiveMap.get(Object key),会先判断key值是否为String类型,如果非String类型,返回null;否则先将key转为小写,然后在caseInsensitiveKeys中查找对应的原始Key值
如:LinkedCaseInsensitiveMap.get("USERID");
1、先将USERID遍小写为"userid"
2、然后在caseInsensitiveKeys.get("userid")去的原始的key "userId"
3、在执行super.get("userId")取得目标值
在JDK1.6中LinkedHashMap的putAll(paramMap)方法是在父类HashMap中实现的,其解决方案是循环遍历paramMap,然后使用子类的put方法插入数据,所以最终在put方法执行时向caseInsensitiveKeys插入了key值得映射。
在JDK1.8中HashMap中putAll却是不再需要遍历调用子类的put方法,以至于putAll时添加的键值对的key值映射在caseInsensitiveKeys中并不存在,所以get时会返回null
LinkedCaseInsensitiveMap继承于LinkedHashMap,LinkedCaseInsensitiveMap可以检测关键字(不区分大小写)的唯一性