0

In Java 1.5, how can I clone an instance of java.io.CharArrayWriter?

CharArrayWriter x = new CharArrayWriter(200);
x.write("foo bar bob");

CharArrayWriter y = x.clone();   //  Object.clone() is not visible!!

Thanks,
mobiGeek

2 Answers 2

4

There is no clone method, but you can use writeTo method.

CharArrayWriter copy = new CharArrayWriter(x.size());
x.writeTo(copy);
0
0

CharArrayWriter is not cloneable. Depending on your actual requirement you can do similar with:

CharArrayWriter y = new CharArrayWriter();
y.write( x.toCharArray() );

Which is essentially the same thing.

2
  • writeTo() is a better solution as it avoids an extra array copy.
    – PSpeed
    Dec 11, 2009 at 3:33
  • False. CharArrayWriter extends Writer which has a write(char[]) method. Check the docs... and anyone else who voted me down on that. ;)
    – PSpeed
    Dec 11, 2009 at 7:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.