Is there any limit on the length of Strings that may be used as a key value into a Map? I would to like to cache some data based on a complex SQL where clause criteria using the where clause as the key. The where clause may exceed 1000 characters but I don't expect it to get much larger than that.
Using a HashMap treats a String as an Object. Hence, ANY String will do, regardless of the length of the string, because ALL Strings, just like ALL Objects, have hashCodes and .equals methods.
One thing you should note, however, is that the .equals operation is O(n) on the size of the String, so the bigger the strings are, the longer it takes to do a compare on .equals.
Also, depending on how well distributed your String hashCodes are (they actually have a pretty good hash method now, if I'm not mistaken, but prior to 1.2, it was TERRIBLE, because it only examined the first 16 characters of the String -- in your case, ALL strings COULD have the same 16 first characters: "SELECT * FROM someTable WHERE ...". Just a warning, if you actually ARE still using 1.2. See http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf ), and your HashMaps load factor, your HashMap could possible degenerate into a linked list, making the amout of .equals operations that must be performed worst case O(n) on the number of Strings in the map.
So, you can use any string you would like, but you will have to pay efficiency penalties for longer strings, and possibly for poor management of your HashMap.
Also, if you are not sure about the max lenght of Strings (theoretically, there is no max, but practically, there is), there is an interesting discussion on it here .
Joined: Jul 31, 2001
Thanks Ernest and Adam for responding to my question. I didn't think there was any special limit so thanks for confirming that for me.