我想实现一个不区分大小写的哈希映射。这个问题本身并不新鲜,但我想添加额外的功能,但不知道要采取什么总体方向。我希望客户能够做这样的事情:
boolean preserve_case = true;
Map<String, MyClass> maplet = new CaseInsensitiveHashMap<MyClass>(preserve_case); // If the client enters true at construction, then the put, get, and remove methods should still be case insensitive, but the entry and key sets should preserve the case that the client used when calling put.
maplet.put("FoO", my_class);
MyClass bar = maplet.get("foo"); // Should return a reference to my_class
Set<Entry<String, MyClass>> case_sensitive_set = maplet.entrySet(); // Since the client input true to preserve order, this entry set should be ["FoO"=my_class.toString()]
我可以很好地处理大部分事情;我只是保留一个HashMap
在后端。当客户放入任何内容时,我会在将其添加到地图之前将其大写。
我只是很难写keySet()
and entrySet()
方法。我希望返回的条目集和键集由映射支持,就像 Java 映射的标准一样。
然而,我能想到的处理这个问题的唯一方法是创建第二个支持数据结构,比如preserved_case_map
,其中包含input.toUpperCase()
=> 作为键值对输入。当客户要求entrySet()
(or keySet()
),我可以通过循环构建返回的条目集preserved_case_map
。这里的问题是,如果我更改了返回的条目集,则不会修改HashMap
,除非我误会了什么......
让我知道这是否有意义,或者我是否使一个简单的情况变得复杂。
您可以使用带有不区分大小写比较器的 TreeMap。 TreeMap 将使用比较器以不区分大小写的方式比较键:
Map<String, Integer> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
map.put("Foo", 1);
map.put("fOo", 2);
System.out.println(map.get("foo")); // prints 2
System.out.println(map.keySet()); // prints [Foo]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)