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.
Ernest Friedman-Hill
author and iconoclast
Marshal
If you want me to be extremely precise, I should say there are no special limits, aside from the intrinsic limits of the String class: a maximum of 2^31-1 characters, I believe.
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 .
- Adam
Jay Damon
Ranch Hand
Joined: Jul 31, 2001
Posts: 279
posted
0
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.
pascal betz
Ranch Hand
Joined: Jun 19, 2001
Posts: 547
posted
0
String.length() returns an int, so its as Ernest said... and this is farfarfar away from 1000 characters :-)
pascal
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
Hey
Long back, once somebody asked similar question that how long array we can declare in Java and Jim (of course I meant Jim Yingst) answered it...which made sense and I confirmed it too
So assuming we have all the memory available to allocate a single String we can maximum go upto Integer.MAX_VALUE as length() method returns "int" and similar thing applies to array's length too..
So in actual case it won't be exactly Integer.MAX_VALUE as we always have something loaded in memory (like class objects, other possible constants)...