Not having any luck finding this, but I'm trying to override the String func in Java. I'm using given source code for a dictionary search, and how it works is it basically hashes all the words. It does it though so that "HI" and "hi" are not the same word. I figure the simplest way is to write my own hash function for String so that "hi" will then hash and reveal "Hi" in the dictionary. How do I do this?
4 Answers
You make a class with a single field, a String.
You @Override equals and hashCode on your class to do case-insensitive stuff.
You store objects of your class in a HashSet or HashTable or whatever.
2 Comments
Similar to @Oli's, but without having to call to...Case before calls
public class CaseInsensitiveMap<V> implements Map<String, V> {
private final Map<String, V> map;
public CaseInsensitiveMap(Map<String, V> map) {
this.map = map;
}
public V put(String key, V value) {
return map.put(key.toLowerCase(), value);
}
/// etc...
}
3 Comments
tr, then yes HI and hı are the same things in case-insensitivity manner, and it still works. Where's the problem?Call String.toUpperCase() before you run the hash function?
4 Comments
The idea has three faults: it is bad, impossible and unnecessary.
It's impossible, because java.lang.String is final. You can't inherit from it, so you can not override any methods.
It's bad in two ways: firstly because you would change the contract and behaviour of one of the core classes. Being able to pass an instance of String that does not behave like String could break literally anything. Secondly, I understand that to do what you want you would have to override equals as well - and this would end with an asymmetric equals (where a.equals(b) != b.equals(a) in case where one of a or b is a plain string and one your special version). I think case insensitive string being equal to an ordinary string was actually an example of a really bad idea in Bloch's "Effective Java".
It's unnecessary, because what you need is an object that holds a String and delegates to it. It could also have a constructor or a static factory method that takes a plain string. Or a case insensitive map, whatever. Plenty of examples in other answers.