I have heard that when you create a string and then shorten it, the original char length is maintained and wastes memory. Is there a simply way to shorten the length of the char after shortening the String length?
Strings are immutable, but there are numerous methods which create new Strings based on existing Strings. One particular example is substring(). Prior to JDK 5.0, if you used substring() on an existing String, you'd get a String using the exact same char backing array as the original. I once had a long file to read in which each line was a record, and I needed to extract the record ID (the first part of the line, roughly a tenth of the total length) and save it in a HashSet. The problem was, this used ten times as much memory as it should have - because each record ID was a String made from substring() which referenced a char which contianed the entirey of each line which had been read - even though 9/10 of that line was data I didn't need or care about. The solution at the time was to use a new String (String) constructor to make a fresh new copy of each ID string - one that did not have any reference to the previous char array. This made it possible to discard all the unnecessary data in the original char arrays.
As of JDK 5.0, it looks like all the methods in String (and StringBuffer) which previously used shared char buffers behind the scenes, have apparently been rewritten to always construct a fresh new char with no references to the old data. I think the end result is that the new methods are a bit less efficient, but also a bit safer (in the sense that it's less likely there will be excess memory used in non-obvious places)..
"I'm not back." - Bill Harding, Twister
subject: Any tips on how to reduce a String's char length?