CaseInsensitive Map Key Java

时间:2016-08-18 19:33:49

标签: java string hashmap case-insensitive

我有一个String我需要String键不区分大小写

目前我正在将CaseInsensitiveString个对象包装在Wrapper类中,我称之为 /** * A string wrapper that makes .equals a caseInsensitive match * <p> * a collection that wraps a String mapping in CaseInsensitiveStrings will still accept a String but will now * return a caseInsensitive match rather than a caseSensitive one * </p> */ public class CaseInsensitiveString { String str; private CaseInsensitiveString(String str) { this.str = str; } public static CaseInsensitiveString wrap(String str) { return new CaseInsensitiveString(str); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if(o.getClass() == getClass()) { //is another CaseInsensitiveString CaseInsensitiveString that = (CaseInsensitiveString) o; return (str != null) ? str.equalsIgnoreCase(that.str) : that.str == null; } else if (o.getClass() == String.class){ //is just a regular String String that = (String) o; return str.equalsIgnoreCase(that); } else { return false; } } @Override public int hashCode() { return (str != null) ? str.toUpperCase().hashCode() : 0; } @Override public String toString() { return str; } } 代码如下:

Map<CaseInsensitiveString, Object>

我希望能够让Map#get(String)仍接受Map#get(CaseInsensitiveString.wrap(String))并返回该值而无需HashMap。然而,在我的测试中,只要我尝试这样做,我的get()就返回了null,但如果我在调用HashMap

之前包装了String,它确实有效

是否可以允许我的CaseInsensitiveString接受get方法的String和String参数,并以caseInsensitive方式工作,无论 Map<CaseInsensitiveString, String> test = new HashMap<>(); test.put(CaseInsensitiveString.wrap("TesT"), "value"); System.out.println(test.get("test")); System.out.println(test.get(CaseInsensitiveString.wrap("test"))); 是否被包装,并且如果是的话,我做错了什么?

供参考我的测试代码如下:

null
value

并返回:

settle()

2 个答案:

答案 0 :(得分:4)

你可以这样做:

Map<String, Object> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

请参阅this question

但是,请注意使用TreeMap代替HashMap的性能影响,正如Boris在评论中所提到的那样。

答案 1 :(得分:0)

这是预期的:

见:

Map<CaseInsensitiveString, String> test = new HashMap<>();

此行告诉MAP仅接受CaseInsensitiveString对象,当您将另一个对象传递给地图时,它将其视为未知密钥并返回null。

您可以将此更改为:

,以获得所需的行为
Map<Object, String> test = new HashMap<>();