Yep, substring MAY (or may not) decide to avoid copying the characters
and simply keep a reference to the char array in the source String.  A
smart substring implementation wouldn't do this if the result string
were quite short or the source string quite long, but apparently the
Android implementation isn't that smart.

The same thing may occur if you do "new String(someOtherString)".

There's probably no guaranteed way to prevent this from happening,
unless you somehow use a char array as an intermediate value.

On Oct 6, 1:50 pm, Alex <a...@appfactory.at> wrote:
> Hi everybody!
> First of all, sorry for my bad english ;-)
>
> After several hours of searching for the cause of a OutOfMemoryError,
> I found a wierd problem with Strings. To keep it simple, trimmed it
> down to something like this:
>
> ArrayList<String> someStringList = new ArrayList<String>(1000);
> for (int i=0; i<1000; i++) {
>     String someBigString = new String(new char[100000]);
>     String someSmallString = someBigString.substring(0,1);
>     someStringList.add(someSmallString);
>
> }
>
> OK, it's not very useful and even though it's a big string, I would
> expect it to work properly, because only one char is stored in the
> list. But in fact, heap is growing rapidly and OutOfMemoryError
> exception will be thrown in 2,3 seconds. And I can't imagin why.
>
> AND NOW the interessting part, a little workaround:
>
> ArrayList<String> someStringList = new ArrayList<String>(1000);
> for (int i=0; i<1000; i++) {
>     String someBigString = new String(new char[100000]);
>     String someSmallString = someBigString.substring(0,1);
>     someStringList.add(someSmallString + "BUGFIX");
>
> }
>
> WTF? Why is this now working?
> The only difference is the concatenated string (someSmallString +
> "BUGFIX")! And as originally expected, with this workaround nearly no
> memory will be used ...
>
> Any ideas? I would appreciate it very much, if someone could give me
> hint. Maybe I'm missing something basic here?

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to