Consider:
String[] segments = {"asdf", "qwerty", "blahblah", "alongerstring", "w349fe3434"};
String fullString = "asdfqwertyblahblahalongerstringw349fe3434";
Is there an efficient way to combine the hashCode()s of each of element in segments in such a way that it equals the hashCode of fullString?
Obviously if I loop over every character in all the segments, I can come up with the same result as fullString.hashCode(), but that doesn’t take advantage of the cached hashCodes in each of the segment string objects. I would like to avoid looping over each character of each segment. Also I can’t cache the looped-over hashcode for segments, because sets of segments might be combined to create a full string.
So basically, I would like something that does this:
int segmentHash = 0;
for(int i = 0; i < segments.length; i++)
{
segmentHash = combine(segmentHash, segments[i].hashCode());
}
assert(segmentHash == fullString.hashCode());
Possible?
Surprisingly, yes.
Looking how the
String‘s hashCode is calculated (s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]), you need to do the following:Edit:
Of course, you need to know additionally the lengths of the segments. Without this information the calculation is obviously impossible.