出于以下原因,我想使用不区分大小写的字符串作为 HashMap 键。
- 在初始化期间,我的程序使用用户定义的字符串创建 HashMap
- 在处理事件(在我的情况下是网络流量)时,我可能会在不同的情况下收到字符串,但我应该能够找到
<key, value>
从 HashMap 忽略了我从流量中收到的案例。
我采用了这种方法
CaseInsensitiveString.java
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null)
throw new NullPointerException();
this.s = s;
}
public boolean equals(Object o) {
return o instanceof CaseInsensitiveString &&
((CaseInsensitiveString)o).s.equalsIgnoreCase(s);
}
private volatile int hashCode = 0;
public int hashCode() {
if (hashCode == 0)
hashCode = s.toUpperCase().hashCode();
return hashCode;
}
public String toString() {
return s;
}
}
LookupCode.java
node = nodeMap.get(new CaseInsensitiveString(stringFromEvent.toString()));
因此,我正在为每个事件创建一个新的 CaseInsensitiveString 对象。因此,它可能会影响性能。
还有其他方法可以解决这个问题吗?
最佳答案
Map<String, String> nodeMap =
new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
这就是你真正需要的。
关于java - 不区分大小写的字符串作为 HashMap 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8236945/