Re: Cloning String object

Discussion in 'Java' started by Will Clark, Aug 23, 2003.

  1. Will Clark

    Will Clark Guest

    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" <> wrote in message
    news:bi82mh$b5f$...
    > 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
    >
    >
     
    Will Clark, Aug 23, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guest

    Cloning Possible?

    Guest, Nov 10, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    402
    Steve C. Orr [MVP, MCSD]
    Nov 11, 2003
  2. Marco Schmidt

    Re: Cloning String object

    Marco Schmidt, Aug 23, 2003, in forum: Java
    Replies:
    0
    Views:
    381
    Marco Schmidt
    Aug 23, 2003
  3. Elhanan
    Replies:
    0
    Views:
    300
    Elhanan
    Dec 27, 2006
  4. Eric Mahurin

    Cloning into an object

    Eric Mahurin, Apr 30, 2005, in forum: Ruby
    Replies:
    3
    Views:
    97
    Charles Steinman
    May 1, 2005
  5. Shea Martin

    cloning object with array members

    Shea Martin, Jan 5, 2007, in forum: Ruby
    Replies:
    7
    Views:
    136
    Stefano Crocco
    Jan 9, 2007
Loading...

Share This Page