在默认的Java API中,您有:
String.CASE_INSENSITIVE_ORDER
因此,如果要使用带有Sorted数据结构的字符串,则无需重写比较器。
String s = "some text here";
s.equalsIgnoreCase("Some text here");
您想要在自己的代码中进行纯粹的相等检查。
只是为了进一步了解有关Java中字符串相等性的任何信息。 java.lang.String类的hashCode()函数“区分大小写”:
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
因此,如果你想使用带有字符串的Hashtable / HashMap作为键,并且像“SomeKey”,“SOMEKEY”和“somekey”这样的键被视为相等,那么你必须将你的字符串包装在另一个类中(你不能扩展) 字符串,因为它是最后一个类)。 例如 :
private static class HashWrap {
private final String value;
private final int hash;
public String get() {
return value;
}
private HashWrap(String value) {
this.value = value;
String lc = value.toLowerCase();
this.hash = lc.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof HashWrap) {
HashWrap that = (HashWrap) o;
return value.equalsIgnoreCase(that.value);
} else {
return false;
}
}
@Override
public int hashCode() {
return this.hash;
}
}
然后使用它:
HashMap map = new HashMap();