Re: Cloning String object

W

Will Clark

Nope, I'm afraid using the code you have is probably the best...

there is a really convoluted way that uses Serializable to clone an entire
object, if that's what you'd like?...

public static final Serializable clone(Serializable src)
{
try {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
java.io_ObjectOutputStream oos = new java.io_ObjectOutputStream(baos);
oos.writeObject(src);
oos.flush();
oos.close();
java.io.ByteArrayInputStream bais = new
java.io.ByteArrayInputStream(baos.toByteArray());
java.io_ObjectInputStream ois = new java.io_ObjectInputStream(bais);
Object dest = ois.readObject();
ois.close();
return (Serializable)dest;
} catch (Throwable th) { return src; }
}

This function does a so-called "deep clone" of most objects in Java (all
that support the Serializable interface) including String, or returns the
same object by reference in case of failure. Not particularily elegant, but
it works well for me!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top