有时候我们会需要一个不区分KEY大小写的MAP,今天介绍一个apache.commons包里的类:
org.apache.commons.collections.map.CaseInsensitiveMap 例子:public static void main(String[] args) { Mapresult = new CaseInsensitiveMap(); result.put("aaa", "ok"); System.out.println(result.get("aaa")); System.out.println(result.get("aAa")); System.out.println(result.get("AAa")); System.out.println(result.get("AAA"));}
输出:
okokokok
而HashMap是要区分大小写的
例子:
public static void main(String[] args) { Mapresult = new HashMap (); result.put("aaa", "ok"); System.out.println(result.get("aaa")); System.out.println(result.get("aAa")); System.out.println(result.get("AAa")); System.out.println(result.get("AAA"));}
输出:
oknullnullnull
若需要把HashMap转为CaseInsensitiveMap,需要putAll,直接等于是不生效的。
正确:
Map map = new HashMap();Map map1 = new CaseInsensitiveMap();map1.putAll(map );
错误:
Map map = new HashMap();Map map1 = new CaseInsensitiveMap();map1 = map;//不生效,依旧区分大小写