[DISCUSSION] Views of immutable objects.

Roman Kennke roman at kennke.org
Mon Jul 16 17:51:16 UTC 2007


Hi Paulo,

Am Samstag, den 14.07.2007, 18:52 +0100 schrieb Paulo Levi:
> I'd like to ask if it would be possible to modify the classes of some
> primitive immutable types for returning immutable read only views.
> For example for strings, when using the document hierarchy, any
> insertString in the GapContent object invokes str.toCharArray(), that
> is implemented like this:
> public char[] toCharArray() {
>     char result[] = new char[count];
>     getChars(0, count, result, 0);
>     return result;
> }
> I'd like if the new didn't exist. 

If you need a read-only view of String to avoid allocation, well, the
String already is read-only. You can access the character data via the
CharSequence interface.

For Swing, there's javax.swing.text.Segment, which also implements this
interface. However, as you noticed, the original char array needs to be
copied (bad design decision if you ask me, but not a big issue either).

Then there's java.nio.CharBuffer, which can create read-only views of
CharSequences too.

Depending on your needs, one of the above might help you or not. I don't
think that a read-only primitive array is possible, and it probably
won't help. If you have a memory leak, make sure you understand how
Strings work and what you are doing. String are a little special in
Java, wrt to memory usage and such, but nothing that can't be solved
with existing features.

/Roman

-- 
http://kennke.org/blog/




More information about the core-libs-dev mailing list