I had a Java program that was using a StringBuilder to build a string from an input stream and eventually it caused an out of memory error when the string got too long. I tried breaking it up into shorter strings and storing them in an ArrayList and this avoided the OOM even though I was trying to store the same amount of data. Why is this?
My suspicion is that with one very long string, the computer has to find one contiguous place in memory for it, but with an ArrayList it could use multiple smaller places in memory. I know memory can be tricky in Java so this question may not have a straight-forward answer but hopefully someone can put me on the right track. Thanks!