In the standard Java API, you have:
String.CASE_INSENSITIVE_ORDER
Therefore, you do not need to rewrite the comparator if you must use rows with Sorted data structures.
String s = "some text here"; s.equalsIgnoreCase("Some text here");
This is what you want for pure equality checks in your own code.
Just for more info on everything regarding string equality in Java. The hashCode () function of the java.lang.String class is case sensitive:
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; }
So, if you want to use a Hashtable / HashMap with strings as keys and have keys such as "SomeKey", "SOMEKEY" and "somekey" are considered equal, you will have to wrap the string in another class (you cannot extend String, so like this is the final class). For example:
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; } }
and then use it as such:
HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();
ɭɘ ɖɵʊɒɼɖ 江 戸 Aug 21 '13 at 13:36 on 2013-08-21 13:36
source share