Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Re: Cloning String object

Reply
Thread Tools

Re: Cloning String object

 
 
Will Clark
Guest
Posts: n/a
 
      08-23-2003
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!

"Erez" <(E-Mail Removed)> wrote in message
news:bi82mh$b5f$(E-Mail Removed)...
> Hi, I know that this has been an issue in the past but I haven't found any
> solution yet.
> Since String.clone() does not exist, how do you clone a Sring variable?
>
> Currently I just do something like:
> clone () {
> MyObj obj = (MyObj)super.clone ();
> obj.text = new String (text);
> return obj;
> }
>
> I hope there is a better way to do this,
> Thanks in advance,
>
> Erez
>
>



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
cloning object with array members Shea Martin Ruby 7 01-09-2007 09:52 PM
deep cloning an object via interfaces? Elhanan Java 0 12-27-2006 06:46 PM
Object creation - Do we really need to create a parent for a derieved object - can't the base object just point to an already created base object jon wayne C++ 9 09-22-2005 02:06 AM
Cloning into an object Eric Mahurin Ruby 3 05-01-2005 02:57 AM
Re: Cloning String object Marco Schmidt Java 0 08-23-2003 04:10 PM



Advertisments