Clone an Object

Hey everyone,
I just had a question about cloning an object.
I have an object and within that object there is a field that holds a "date".
I want to clone the object x number of times (x is user input) and each clone the "date" is the next day.
So the second clone's "date" value would be the next day after the first clone's "date" value. I also want each clone stored into an array of that object.
I have a date class and within that date class is a method called "nextDay" which changes the date to the next day.
I hope that makes sense.
Anyways, the way I went about it was this:
Object original = new Object();
drawCount = user input;
Object[] array = new Object[drawCount];
array[0] = original;
if(drawCountInt > 1)
     for(int j = 1;j <= drawCountInt;j++)
        Object daClone = (Object) original.clone;
        daClone.date = daClone.date.nextDay();
}Now that seems like it would work once.
I am trying to figure out, how would I increment the date in a loop?
I could not figure out a way to use the counter to maybe make the nextDay happen more often.
I could not also find a way to make a clone of a clone inside a loop and just use the nextDay on that.
How would I make a clone off the latest clone inside a for or while loop?
Sorry if any of this seems a little unclear. Feel free to ask questions of course.

So something like this then?
if(drawCountInt > 1)
{     Array[1] = (Object) original.clone;
         for(int j = 1;j <= drawCount;j++)
                   Array[j] = (Objectt) Array[j].clone;
                   Array[j].date = Array[j].date.nextDay();
}

Similar Messages

  • Why clone() in Object Class is protected

    hi,
    Why clone() in Object Class is protected
    Why finalize() in Object Class is protected
    Waiting for your reply
    suresh

    Why clone() in Object Class is protectedObject's clone() is meant to provide a generic cloning facility as the assistance for the types implementing Cloneable but not as a public ready-made method. Object's clone() should be overridden for those types to provide a meaningful implementation (maybe relying on Object's clone). Object's clone() being public were an invitation to try to clone every object, regardless of its being cloneable or not. For a type to be cloneable, it is necesary for this type in implement Cloneable, a no-method interface. While at writing the class and declaring it as Cloneable, it is not much more work to provide a clone() implementation. It is the responsibility of the author of a class to decide whether it should be cloneable and if yes, how it should be cloned.
    Why finalize() in Object Class is protected"finalize" is meant for the VM to invoke is as defined by the specification.
    Encapsulation implies everything should have the smallest scope, the most restrictve access which is still appropriate.

  • Is this write way to clone a object?

    All,
    I this the correct way to clone a object? if not so can anyone point me the right way to do that. Because this method is taking longer time to execute.
    import java.io.*;
    public class ObjectCloner
        public ObjectCloner()
        public static Object clone(Object obj)
            throws Exception
            ByteArrayOutputStream bstream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bstream);
            out.writeObject(obj);
            out.close();
            ByteArrayInputStream binstream = new ByteArrayInputStream(bstream.toByteArray());
            ObjectInputStream oin = new ObjectInputStream(binstream);
            Object newobj = oin.readObject();
            return newobj;
        public static int sizeOf(Object obj)
            try
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bstream);
                out.writeObject(obj);
                out.close();
                return bstream.toByteArray().length;
            catch(Exception ex)
                ex.printStackTrace();
            return 0;
    }

    calvino_ind wrote:
    i might be wrong, but i think there are some really easier ways to clone an object:
    public class Age {
    int numberOfYears;
    public Age(int numberOfYears) {
    this.numberOfYears = numebrOfYears;
    public Object clone() {
    return new Age(this.numberOfYears);
    No! This is very wrong. For this simple example, all one needs is class Age to implement Cloneable and
    public Object clone() {
             return super.clone();
    }which will automatically give you a shallow clone of the the class.
    Consider what ill happen with your approach when one clones superclasses of class Age.
    Edited by: sabre150 on May 26, 2008 3:42 PM

  • Is it possible to clone an object from one image and paste it on another image?

    Is it possible to clone an object from one image and paste it on another image in Aperture?

    As Frank said,
    but Aperture has a nice clone tool - the drawback is, that it only works within one image.
    What I sometimes do - as a workaroud, when I want to use the clone brush, is to combine the image I want to clone from and the image I want to clone into, into one single image by printing them together to pdf as jpeg. Then I can clone from the second to the first, for example, to be able to add an fairy to a flower: Picking up the head of the fairy in the right image and brushing it into the left one. Occasionally I prefer the Aperture brush to the Photoshop lasso.

  • What is the need to clone  an object

    What is the need to clone an object
    give me the scenarios where we use cloneable interface

    In a very simple statements,
    clone method will return the new object with the
    SAME SOURCE STATE. Where as
    creating an object using "new" will give completely
    new object.According to whom? I was under the impression that the state of the object returned by calling close was not defined except from what is returned by the Object class.
    As for clone being faster than constructors, it can be. It depends on what the constructor does. For instance, I'm sure its faster to clone an ArrayList than to create a new one by passing the old one into its constructor. Depends on the implementation of the constructor vs. the implementation of the clone.
    Again, do not expose clone because its behavior is not defined. Create an interface with a methd on it, and define what that method returns. Then use clone to create your base object to construct the copy to return.

  • How to Clone  inherited Object ?

    According to the rule of cloning a object can be cloned only if
    it implements Cloneable interface ? In the following example
    class B extends class A which does not implement Cloneable interface,class B does implement Cloneable interface.
    when I try to clone an object of class A in class B it is very
    allowing to be cloned which is a contradictary?Please go through the
    example and suggest what is wrong ?
    class A
    int v = 100;
    public Object Clone()
    return new A();
    class B extends A implements Cloneable
    public static void main(String args[])
    A a = new A();
    A b = null;
    b = (A)a.clone();
    System.out.println("Value of v1 :" +a.v1);
    System.out.println("Value of v1 :" +b.v1);
    Thanks for your valuable help

    According to the rule of cloning a object can be
    cloned only if
    it implements Cloneable interface ? In the following
    example
    class B extends class A which does not implement
    Cloneable interface,class B does implement Cloneable
    interface.
    when I try to clone an object of class A in class B it
    is very
    allowing to be cloned which is a contradictary?Please
    go through the
    example and suggest what is wrong ?
    class A
    int v = 100;
    public Object Clone()
    return new A();
    class B extends A implements Cloneable
    public static void main(String args[])
    A a = new A();
    A b = null;
    b = (A)a.clone();
    System.out.println("Value of v1 :" +a.v1);
    System.out.println("Value of v1 :" +b.v1);
    Thanks for your valuable helpApart the fact that like that program cannot function, you didn't clone anything. You've just created another instance of class A!
    Cloning means to create a copy of an existing object with aonother one having exact members (name, value, behaviour) like the first one!
    Try to replace this piece of code:
    A a = new A();
    a.v = 500;
    A b = null;
    b = (A)a.clone();
    System.out.println("Value of a.v :" +a.v);
    System.out.println("Value of b.v :" +b.v);
    and write "Clone" method like this: "clone". See that you'll obtain:
    Value of a.v :500
    Value of a.v :100
    good luck!
    m

  • Clone() and object copys

    I have been reading about String and arrays and trying to understand the difference between clone() and system.arraycopy..... Here are my questions regarding this:
    1. Why isn't there a deep copy for String, especially if we all need to keep writing code to make up for it?
    2. What happens when using the assignment operator for a non-array object, say String? Is it getting a reference, or new memory with a copy of the values? eg.
    String strThis= "Hello Java";
    String strNew = strThis;

    I have been reading about String and arrays and trying
    to understand the difference between clone() and
    system.arraycopy..... Look at the arguments for each method and read the JavaDoc - clone creates an object, whereas arraycopy copies a subarray to an existing subarray.
    Here are my questions regarding
    this:
    1. Why isn't there a deep copy for String, especially
    if we all need to keep writing code to make up for
    it?Sting objects are immutable, so what would you gain from a deep copy? What code do "we all need to keep writing to make up for it"?
    2. What happens when using the assignment operator for
    a non-array object, say String? Is it getting a
    reference, or new memory with a copy of the values?
    eg.
    String strThis= "Hello Java";
    String strNew = strThis;It gets a copy of the reference.

  • Don't clone list objects, just parent

    I have a need to create an object and add it to the parent list. I am currently doing it like this.
    UnitOfWork uow = session.acquireUnitOfWork();
    MyChild newChildClone = uow.newInstance(MyChild.class);
    MyParent parentClone = uow.registerObject(parent);
    newChildClone.setParent(parentClone);
    parentClone.getChildren().add(newChildClone);
    uow.commit();This clones all of the existing children of the parent, because they are loaded from the parentClone. How can I add the new child to the list without cloning all of the existing children?

    Probably best to not worry that much about it.
    If the collection is really large you may consider,
    - If you use weaving (such as when using JPA and an agent, but also usable in the native API with some effort), and use attribute change tracking (default with weaving) and lazy,
    then the add() will not trigger the collection to be instantiated. (must be using EclipseLink for this)
    - Otherwise, you could just not add it, and either assume the collection is not instantiated, or refresh the object or invalidate the object after the commit.
    - Or just don't map the OneToMany relationship if you really never want to instantiate it, just query for it if you really need it.
    James : http://www.eclipselink.org : http://en.wikibooks.org/wiki/Java_Persistence

  • Always override: toString(), clone(), equals(Object obj)?

    In classes that I write Is there any reason to not always override:
    public String toString();
    public boolean equals();
    public Object clone(Object obj);Further, why not always provide a default Comparator ?
    public Comparator getDefaultComparator();This seems logical?

    kakusaretasuna wrote:
    thank you.
    I am just beginning to learn Java, and so I am making a checklist of things to do when I write a class.
    When it makes sense, I will always implement:
    toString()
    clone()
    equals()
    getDefaultComparator()getDefaultComparator? No, I wouldn't do that. Where did you get that idea from?
    And if you override equals, you should always override hashCode as well, and vice versa.
    As a rule, I do not override those methods unless I have a specific reason to.
    And, I learned that by default a Java class is not Serializable . Therefore, for each of my
    classes, I need to adjust them to safely be Serializable , and then declare them Serializable Only if there's a reason to serialize them. Again, it doesn't make sense for all classes, or even most.
    This makes sense to me, however, I don't want to appear foolish to exeperienced developers. For example, I learned that:Worry less about appearing foolish and more about learning. Everybody had to start somewhere, and this stuff is generally not intuitive. Nobody cares if you don't automatically know it all.
    >
    private final void foo(); // "final" is annoying and foolish?As with most things, there are at least two schools of thought on that. In general, I don't make methods final unless I specifically don't want them overridden. Some people feel you should declare them final by default, and only remove the final in cases where there are specific reasons to override them. Neither is right or wrong. It's mostly a matter of convention, and somewhat a matter of context.
    private void foo() { this.privateMethod(); } // "this" is annoying and foolish?I personally hate using "this" when it's not necessary, and it's never necessary in the case of method calls. It doesn't even add any clarity. It's just clutter.
    >
    I am sure there are many other construts that experienced developers avoid.Yes, but don't worry about learning them all right now.

  • Clone enity object, so I can change one field

    Can you lock a record in BC4J and copy as an insert it with new changes? For example, if I have an order record (order entity object that is equivalent to one record in the database) to be copied so the old record can be save for historical purposes and a field in the copied record can be modified.

    You could adopt a technique similar to the one I describe in this "Dive into BC4J" web log posting...
    http://radio.weblogs.com/0118231/2003/08/07.html
    You could do something similar at entity level by creating a new entity instance using EntityDefImpl.createInstance(), then copying the attributes from the old to the new with a similar bit of code.

  • How to clone a user-defined object?

    Hello,
    I need to clone an Object[] array (propArray) that holds objects of Integer, Double, Boolean type, along with objects of user-defined ClassA, ClassB, ClassC type. The matter is that the ClassA object isn't being cloned, while the rest of the user-defined objects are cloned just fine.
    In more detail, ClassA has two properties:
    public class ClassA implements Cloneable{
       private String penaltyFor;
       private Penalty[] penaltyArray;
       protected Object clone(){
          try{
             ClassA o = (ClassA)super.clone();
             o.penaltyFor = this.penaltyFor;
    //         o.penaltyArray = (Penalty[])penaltyArray.clone();  //This ain't working.
             //But neither does this :(.
             int penCount = this.penaltyArray.length;
             o.penaltyArray = new Penalty[penCount];
             for(int i = 0; i < penCount; i++)
                o.penaltyArray[i] = (Penalty)this.penaltyArray.clone();
    return o;
    } catch(CloneNotSupportedException e){ throw new InternalError(); }
    The Penalty class contains properties of primitive type and here is its clone() method:
    public class Penalty implements Cloneable{
       private String penaltyDesc;
       private int lowLimit, upperLimit, penaltyValue;
       protected Object clone(){
          try{
             Penalty o = (Penalty)super.clone();
             o.penaltyDesc = this.penaltyDesc;
             o.lowLimit = this.lowLimit;
             o.upperLimit = this.upperLimit;
             o.penaltyValue = this.penaltyValue;
             return o;
          } catch(CloneNotSupportedException e){ throw new InternalError(); }
       }I don't know what else to try. I suppose the problem is the Penalty[] array, but I may be wrong. An alternative would be to use Copy Constructors, but it will cause too many changes to the code, since the clone() method is used for the propArray copy in many places and the ClassA object is a late addition to the propArray (unfortunately it wasn't planned to exist from the beginning).
    Thank's.

    class ClassA implements Cloneable{
       private String penaltyFor;
       private Penalty[] penaltyArray;
       public Object clone(){
          try{
             ClassA o = (ClassA) super.clone();
             if (penaltyArray!=null){
                o.penaltyArray = (Penalty[]) penaltyArray.clone();
                for(int i = 0; i < penaltyArray.length; i++) {
                    Penalty penalty = this.penaltyArray;
    if (penalty!=null)
    o.penaltyArray[i] = (Penalty) penalty.clone();
    return o;
    } catch(CloneNotSupportedException e){
    throw new InternalError();
    class Penalty implements Cloneable{
    private String penaltyDesc;
    private int lowLimit, upperLimit, penaltyValue;
    public Object clone(){
    try{
    return super.clone();
    } catch(CloneNotSupportedException e){
    throw new InternalError();
    If your Penalties are immutable, you don't need to clone them -- rather,
    make then unclonable, like Strings.

  • RegisterObjet (for a new object) return a clone form a different object

    Hello,
    when I register a new object with registerObject method, I sometimes receive an object from the same class but a clone from an other objet.
    How is that possible ?
    thanks
    Annabelle

    Hello Annabelle,
    When you call registerObject(someObject), TopLink will perform an existence check to see if the object passed in is new or existing, then return a working copy of the object passed in. It the object was previously registered, it will pass the same working copy back, otherwise, it will clone the object passed in to use as the working copy.
    Are you using sequencing?
    If registerObject is passing back the same working copy for multiple new objects, there might be a problem with the object's primary key - which is used for identity.
    Try printing off what is in the identity maps using the session.getIdentityMapAccessor().initializeIdentityMaps() api on the UnitOfWork. This should show all the objects in the cache as well as the primary keys they are cached under, which might help to identify the problem object and how it got in the cache.
    Best Regards,
    Chris

  • Help in Object.clone()

    Hi All,
    why i am unable to call the clone() in Object class from the subclass of the Object class.
    Obj o1 = new Obj(); //Simple bean class.
    o1.clone() //error.error:- the method clone() from the type Object is not visible
    note : clone() is protected and native.
    Thanks
    Dorairaj M
    Edited by: DoraiRaj on Apr 13, 2010 9:02 AM

    malcolmmc wrote:
    dcminter wrote:
    I don't see the big problem.No a big problem that I know of - it just didn't offer anything you couldn't do with copy constructors and but did put up minor obstacles as well as adding an unnecessary method to Object.What it does offer is a method to copy the fields of an object all in one go, rather than having to list them or use introspection. A copy constructor wouldn't do that for you. Also you can clone a superclass reference and have all the fields of a subclass still copied. A copy constructor is unlikely to do that.Exactly. That's why I figured clone() might be preferred--the polymorphism more than the all-in-one bit. I guess it depends on your requirements.

  • Why would Object.clone cause IncompatibleClassChangeError

    I have 3 classes,
    B, A, and M
    public class B implements Clonable
    public Object clone() throws CloneNotSupportedException
    { return super.clone(); } // basically Object.clone()
    public class A extends B { ... }
    public class M extends A { ... }
    A and M do not override clone
    sometime, not all the time, I get this IncompatibleClassChangeError when
    M.clone() is invoked. I don't know why, since I'm not doing anything profound, or why it would happen only some times. I'm running java 1.4.2_04-b05

    You can try having each of your subclasses also implement Cloneable. Granted, this is a bit of copy-pasted code to keep calling super.clone(). See if that fixes it.
    - Saish
    "My karma ran over your dogma." - Anon

  • When do we override our own clone method not the Object class clone method

    Hi,
    I have a confusion in overriding clone method.We can create clone object by writing Object.clone() but some times I have seen writing our own clone method ,when do we write this,also clone() is defined protected and when we write our own clone it is said to write it public,why?
    Thanks
    Sumit

    protected methods can only be called in the same class and it subclass. You can make clone protected if this is all you need.
    However if you need to clone() the object from another class, it need to be public.
    This is the same for any method.
    Also as Object.clone() is protected you cannot make it private or package-local (this is true of any protected method)

Maybe you are looking for

  • Installing CS5.5 Master Collection on a Mac and everything installs except ACROBAT X PRO

    Screenshot of errors.

  • Protection type for Acrive Data Guard

    Hi all, I am looking at implementing a 11G R2 active data guard solution and need to do live reporting from the physical standby database. I need confirmation of the protection mode I will need. (I think it's Maximum Protection). Many thanks VicC

  • Clling a Compiled HTML HelpFile Topic from Web Form

    Ben: I'm a project manager on a development project in a client's Oracle environment. We want to deliver help files from the unix server when a user presses the F1 key or the ? button. The application runs on the server and users have access to it th

  • HTML: attribute title and caption

    Hi, Is there any reason that neither title or alt is not shown to users hovering the image? Doesn't w3c state that title should be shown? example: Also why is table-caption show AFTER the table? Isn't that very onlogical? example: <table><caption>Tab

  • Web Performance (Static vs Dynamic pages)?

    Hello all, I am building a web site like http://www.bizrate.com/buy/browse__cat_id--402,de_id--300.html and want to know if I use jsp to generate web pages(e.g. a user browse by Resolution), then each time the server would recompute and get the same