Copy objects ('deep copy')

Could you help me please, I'm trying to perform a copy between object A and object B they are different instances of the same object. Object A contains other objects inside it and goes like this into a level of 4 or 5 object inside others. The purpose is to copy the attributes from objects B which have a value of null in the object A so I have to go thru all the objects and compare each attribute. I thougth about some solutions but they are to complex and difficult to implement, could you give some ideas...
PF

Implement a copy method in each of your objects, that
1. Copies all simple datatypes and objects directly to an object of the same type
2. Invokes your copy method on all non-simple object attributes
Your copy method should have a consistent method signature of the form..
public void myCopy(thisObject obj);This is not an overly complicated solution.

Similar Messages

  • Object comparison tool with reflection

    I'm writing some piece of code to compare two java objects without equals method. I use java reflection to get all the declared fields in the class of the object and all the objects that resides in it. It goes inside of all the objects and collection objects recursively. It gets all the declared fields of the higherarchy. My objective is to get all these field values for both root objects to be compared and then compare these fields to compare the two objects. I can not use equals method as it is implemented in some classes of the package I use. The problem I face is that when I traverse into a collection object, it has no name (can't get a name from reflection) and when there are collection objects inside collection objects the situation gets worse. I don't have a way to identify the declared values. If duplicated values are there in a collection, I don't have a way to store them for comparison as they are not unique.
    Is there any tool available which does this comparison with the use of reflection? That is, given two java objects, it lists their differences. Any Idea?????

    Thank you for your reference. What I actually need is to identify the positions of differences between two objects and show the differences in an higherachycal way.
    So I want to get the positions (which fields are different) to graphically show in a tree like thing. What I do currently is like as follows.
    1. Traverse both objects deep inside to primitive types, including collection, collection in collections, objects, etc and put them in separate hash maps.
    2. These hash maps contain, key -> path from the root to primitive field and value -> the primitive value of the field.
    3. Finally take these two hashmaps, take one's key and try to see whether the other map contains the key. I it doesn't the field is a new one. If it has, then check its value for equality. Then I know the path where differences occur and then later, in any representation, I will know which field to be marked as different.
    But the problem I face with this structure is that, When I traverse into a collection object, it doesn't have a name for its items. So I get a problem of how to get the key (actually path). If this problem can be solved, my comparison is completed.
    If anyone knows a tool that does the same thing, let me know so that I can analyse how they do so. Or give me a help on what to do with my structure of comparison. I can't call objects equals method as my other packages have modified this equals method. So I have to get each and every declared field value and see whether the given two objects are of the same with their declared values and fields.

  • Turning off Isolation Mode feature?

    Working with the german Version, therefore not sure if its called "Isolation Mode" in the english version too.
    Problem is, that working under pressure an aditional klick on an object happens very fast. That always throws me into that useless Isolation Mode. To me this "feature" is of absolute NO use at all and I'd wish I could turn it off. Anybody with a clue to get rid of it?
    Manuel

    You can also mark jesseham's answer as the correct answer it will be helpful to others
    but as both prior posted suggested you might want to keep this on it is extremely helpful and working in groups can
    speed up things as well so you really need it then keep in mind you can have groups within groups and this is helpful for isolating
    objects deep within a group.
    Most important it protects the rest of the group(s) extremely useful.

  • Values of dynamic selections for LDB DDF

    Hi
    I have to customize a SAP standard program which is using LDB-DDF. As per client requirement, we have to add a few select statement and there we have to add the selection criteria of dynamic selections.
    The problem I am facing is that I dont know how and where i can track the values given in the dynamic selection screen.
    I did some research and I found out that values entered in the dynamic selections is stored in complex data object (deep structure) but I am not able to find it where and how we can use it.
    The name of the SAP standard program is RFDZIS00.
    Thanks in advance
    Bhav

    Hi,
    In SE36-> DDF-> select the Selections radio button.
    Menubar Extras->Selection Views-> Here you can change the "origin of view" which is created by SAP or we can create our own views under "origin of view" CUS.
    Best Regards,
    Mohan,

  • Curiosity about Threads

    Good day to all.
    I have been working recently on streamlining an online application that displays / manages info from a db. In the application there are multiple views that can be called. A view expands a collection of elements so that sub elements can be viewed. There is no limit as to the depth of the objects. Generally though no more than 5 objects deep.
    The application has been plagued with high memory overhead and slow performance.
    When a user chooses to "collapse" an object, the object goes to it's deepest object removes it, moving upwards until it has no more sub objects in memory. The user was having to wait for this action to take place before the display would return.
    I added a Thread to handle the object collapse. now the object re displays as if it was collapsed ( a speed enhancement ). The true removal of sub objects happens in the thread.
    The interesting side effect of this is the memory footprint was reduced by about 25% after this change. A not intended but welcomed effect. I think this happened by reducing the amount of stuff happening in the main thread of the application, allowing the garbage collection to run more efficiently.
    Interested in other ideas / points of view.
    Thanks

    Interested in other ideas / points of view.Beeing a programmer requires you to think for yourself
    you know. It's hard and not everybody is cut out to do
    this kind of work!
    If you don't have it in you, quit now, that's my point
    of view.Not a little too harsh?
    Looks like he/she's done some thinking...
    Dorkey,
    I would imagine that any time you do less, you should take less memory.. It is a good observation that waste and cruddy code that takes up cycles and memory pointlessly should be avoided...
    ~David

  • Powershell and Workflows

    Hi
    When you need to change answers or holidays you use the get-csrgsworkflow and put it in an variable.
    How do you then delete e.g. option 5 an easy way?
    The only way I have found to do it, is creating an foreach loop and then find the answer with the DTMF 5 e.g. and then delete it that way, but I doub that's the easiest way :)
    Anyone have any inputs?
    Regards Lars.

    I was still thinking about this.  One item I neglected to mention, not sure if you came across it and already knew or not but I felt I should bring it up.  If you modify $wf, keep in mind you're just modifying an object in memory, not the
    direct object itself so the changes won't be saved.  To write the data back, you need set-CsRgsWorkflow.  Following the examples here:
    http://technet.microsoft.com/en-us/library/gg425845.aspx
    When you've made all of your changes and are ready to write it back to the response group, you would run:
    Set-CsRGSWorkflow $wf
    Now, that said, rather than pushing objects deeper into variables such as $al, it would be easier just to keep working with $wf.  Then, the whole sequence would look something like this:
    $wf = Get-CsRgsWorkflow -name "Your Response Group"
    $wf.DefaultAction.Question.AnswerList.Remove($wf.DefaultAction.Question.AnswerList[4])
    Set-CsRgsWorkflow $wf
    Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question please click "Mark As Answer".
    SWC Unified Communications

  • Regarding Dimensions of Array

    Hi ..well i am just wondering wht is the limit to Dimension of Array in Java. my ultimate goal is to handle large matrices.
    Looking forward for your response..thanking u ..!!

    Hmmm... that question could be interpreted in at least two ways.
    1. How many dimensions can an array type have? I believe the answer is around 255.
    2. How many levels of arrays can be stored in any array? This is limited only by available memory.
    Remember that "multidimensional arrays" are really just arrays of arrays, and that arrays are objects. Thus, you could have an array of objects whose elements are actually arrays:
    Object[] deep = new Object[10];
    deep[0] = new Object[10];
    ((Object[]) deep[0])[0] = new Object[10];
    ((Object[]) ((Object[]) deep[0])[0])[0] = new Object[10];
    // etc.Actually, an element of an array can be a reference to the array itself:
    Object[] recursive = new Object[1];
    recursive[0] = recursive;so in a sense that is a "bottomless" array!
    If you're willing to code the array accesses with lots of casts, you can handle any number of dimensions, and even arrays of "ragged" dimension.

  • ZLMMirror SLE11-Debuginfo-Updates-patches

    I have been mirroring some of the repositories from Novell (nu) to my environment.
    I have working OES2, SLES10 and SLED10 (SP2), when downloading SLE11-Debuginfo-Updates-patches I stumble in the error:
    --------- cut
    Error: An error occurred while trying to create the bundle "/Bundles/Novell Updates/SLES11/SLE11-Debuginfo-Updates-patches/patch-dbgsp0-openssl-CVE-2009-1386.patch,openssl-CVE-2009-1387.patch_SLE11-Debuginfo-Updates". (An error occurred while trying to create the object.)
    com.novell.zenworks.zlmmirror.server.MirrorServerE xception: An error occurred while trying to create the bundle "/Bundles/Novell Updates/SLES11/SLE11-Debuginfo-Updates-patches/patch-dbgsp0-openssl-CVE-2009-1386.patch,openssl-CVE-2009-1387.patch_SLE11-Debuginfo-Updates".
    at com.novell.zenworks.zlmmirror.server.ZLMLocalServe r.createPackageBundle(ZLMLocalServer.java:1640)
    at com.novell.zenworks.zlmmirror.server.CatalogProces sor.createLocalBundle(CatalogProcessor.java:494)
    at com.novell.zenworks.zlmmirror.server.CatalogProces sor.processBundle(CatalogProcessor.java:257)
    at com.novell.zenworks.zlmmirror.server.CatalogProces sor.processCatalog(CatalogProcessor.java:135)
    at com.novell.zenworks.zlmmirror.server.ZLMLocalServe r.update(ZLMLocalServer.java:732)
    at com.novell.zenworks.zlmmirror.MirrorSession.mirror (MirrorSession.java:513)
    at com.novell.zenworks.zlmmirror.MirrorSession.execut eCommand(MirrorSession.java:488)
    at com.novell.zenworks.zlmmirror.MirrorSession.execut e(MirrorSession.java:283)
    at com.novell.zenworks.zlmmirror.ZLMMirror.executeMir rorSession(ZLMMirror.java:279)
    at com.novell.zenworks.zlmmirror.ZLMMirror.main(ZLMMi rror.java:152)
    Caused by: com.novell.zenworks.zlman.services.coreapi.admin.C oreAPIFault={_Message=An error occurred while trying to create the object.,_Type=5}
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Construc tor.java:274)
    at java.lang.Class.newInstance0(Class.java:308)
    at java.lang.Class.newInstance(Class.java:261)
    at com.novell.zenworks.zlman.services.coreapi.admin.C oreAPIFaultMarshaler.deserialize(CoreAPIFaultMarsh aler.java:35)
    at com.sssw.jbroker.web.soap.LiteralEncodingStyle.rea dObject(LiteralEncodingStyle.java:433)
    at com.sssw.jbroker.web.soap.LiteralEncodingStyle.rea dObject(LiteralEncodingStyle.java:410)
    at com.sssw.jbroker.web.soap.LiteralEncodingStyle.rea dObject(LiteralEncodingStyle.java:372)
    at com.sssw.jbroker.web.core.InputStreamImpl.readObje ct(InputStreamImpl.java:278)
    at com.novell.zenworks.zlman.services.coreapi.admin.C oreAPIBinding_Stub.createPackage(CoreAPIBinding_St ub.java:5061)
    at com.novell.zenworks.zlmmirror.server.ZLMLocalServe r.createPackageBundle(ZLMLocalServer.java:1621)
    ... 9 more
    Caused by: com.sssw.jbroker.web.portable.ApplicationException
    at com.novell.zenworks.zlman.services.coreapi.admin.C oreAPIBinding_Stub.createPackage(CoreAPIBinding_St ub.java:5068)
    ... 10 more
    An error occured while processing the request. Please check the log file for details
    ----------- cut
    I suppose the cause is due the filename he is suppose to download and "install" into ZLM 7.3 have a comma (" ,") in the filename itself, which is very unusual.
    Could anyone confirm if has been experiencing the same problem, if there is any known patch (I searched for this and so far nothing), is this a bug on the ZLM or in the repository?
    Any ideas?
    Regards,

    Originally Posted by tarvindkumar
    This is already known issue under ZLM caused due to eDir's Object length
    (FDN) limitation in the Tree. This prevents the object creation too deep in the ZCC folder hierarchy or if the bundle name if very long such that it exceeds the Object RDN length 128. See below ZLM URL . Edir might have documented it
    Novell Documentation
    Well, according with the documentation you sent, we have the following information:
    An error occurred while trying to create the bundle. (The object could not be created. This could be because the name is too long, or the object is too deep in the folder hierarchy)
    Source: ZENworks 7.3 Linux Management.
    Explanation: The error message is displayed because of the object FDN (Fully Distinguished Name) limitation of 256 characters in eDirectory when you create a bundle object either in ZENworks Control Center or by using the zlman command, or during mirroring.
    Action: Do any of the following:
    Do not create the bundle object deeper in the folder hierarchy, or with long names.
    Ensure that the total FDN of the bundle object from its root container in eDirectory does not exceed 256 characters.
    The error has been generated due a path+name that is about 150 characters, if it was 128, probably I would agree that it could be a problem. In the previous version actually that was a problem because of the sizes and it was already solved with actions in the database, therefore according to the documentation the limitation is 256, like the previous solution proposed.
    Then I got a little bit confused, the newest versions (in this case IR2 and IR3) returns to the lack of capabilities (in path sizes) encountered on the 7.3 with no patches?
    The comma in the name bothers me a lot, and also bothers me that this sort of naming is wrong and possibly giving problems and no one dare to change it... why??
    Regards,

  • CS3 Copy and Paste objects - changing ID names

    Hi all,
    That subject doesn't describe things as accurately as I'd
    like.
    But here's the behavior my new CS3 is doing that I'd like to
    stop if
    possible.
    If I have an object (Div tag or whatver.., maybe an entire
    set of nested
    tables 3 nests deep).
    If, in design view, I copy a selection, then paste in a
    different spot, I
    noticed that the style I had associated with the ID of that
    element no
    longer showed.
    That's becuase CS3 changed the ID of the object by adding a
    2, or 3 or 4 as
    the iterations progress with each paste.
    I understand that in what I described, that's meant to help,
    don't want more
    than one item of the same ID (classes should be used then
    instead).
    But that aside, how can I turn off the behavior of CS3
    changing my ID names.
    I'd rather handle that myself.
    Apologies if it's in an easy to find spot, if so I must have
    looked right
    over it.
    Thanks
    -Dave

    Very very annoying then.
    "Vic Mitnick - Adobe" <[email protected]>
    wrote in message
    news:f2g7f3$7ct$[email protected]..
    > Sorry, there's no way to turn this off.
    >
    > - Vic Mitnick
    > Dreamweaver Engineering
    > Adobe

  • Creating a deep copy

    I wrote a stack implementation using a LinkedList, I have null constructor to create the first stack and it works fine but now i have to create a copy for a second stack using the element of the first constructor
    this my code
    import java.util.LinkedList;
    public class Stack<T>{
      private LinkedList<T> stack;
      public Stack(){
        stack =  new LinkedList<T>();
      public Stack(Stack<T> s) {// the problem is here it compile but when i run
                                                     // the program the second stack raised an exception because is empty
                                                     // i want to create a deep copy with the elements of the first stack
         stack = new LinkedList<T>();
      public boolean isEmpty(){
      return stack.isEmpty();
      public void push(T item){
       /*method to add object information
        *pre the object is not full
        * pos: the object is inserted
          stack.addFirst(item);
      public T top() throws EmptyStackException{
        if (!stack.isEmpty()){ 
          return stack.getFirst();
        else{
          throw new EmptyStackException("StackException on top " + " Stack empty");
      public T pop() throws EmptyStackException{
        /*method to remove an element of the stack
        *pre the object is not empty
        * pos: the object is remove
        * response throws an exception
        if (!stack.isEmpty()){ 
          return stack.removeFirst();
        else{
          throw new EmptyStackException("StackException on top" + "stack empty");
    public int numElements(){
        return stack.size();
    public void clear(){
      stack.clear();
    public class EmptyStackException extends Exception{
            public EmptyStackException( String message){
              super(message);
    }

    wel well... are you doing this on a mobile phone???
    neways to get to ur question u can use the clone() method to generate a clone of your object which is the same as a deep copy for eg:
    public class CloneTest{
        CloneTest test1 = new CloneTest();
        CloneTest test2;
        CloneTest(){
          //Some initialization code;
        CloneTest(CloneTest temp){
             test2 = test1.clone();
    }clone is a method of the object class.

  • Copying objects

    Hi!
    How can I make a copy of an object? I've posted this problem yet another time, but the answers didn't work...
    I only want to copy an array x into an array y and the possibility to change x without changing y at the same time (=> without referencing):
    source:
    int x[]={1,2,3,4,5};
    int y[]= new int[5];
    y=x; //A
    for (int i=0;i<5;i++) System.out.print(x); //1 2 3 4 5
    for (int i=0;i<5;i++) System.out.print(y[i]); //1 2 3 4 5
    x[0]=0; x[1]=0; x[2]=0; x[3]=0; x[4]=0; //C
    for (int i=0;i<5;i++) System.out.print(x[i]); //0 0 0 0 0
    for (int i=0;i<5;i++) System.out.print(y[i]); //0 0 0 0 0
    With this code, I get a reference for x in y (A), so when I change the values of x (C) the values of y are also changed.
    How can I get a COPY of x into y? I've tried it with "int y[]=x", but this also doesn't work. By the way, the assignment should be in a loop, so initializing for copying isn't good...
    Thanks! Chris

    I think this might help you people. There is a concept called deep copy. This does not reference as you people have problem. This works on any object, but The only requirement is that the object in question should be serializable.. As for as any object[] (arrays) take each object from the array and deep copy it and put in the new array.
    // this is  a static method to make a deep copy of any object.
       public static Object deepCopy(Object oldObj) throws Exception
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
          try
             ByteArrayOutputStream bos =
                   new ByteArrayOutputStream(); // A
             oos = new ObjectOutputStream(bos); // B
             // serialize and pass the object
             oos.writeObject(oldObj);   // C
             oos.flush();               // D
             ByteArrayInputStream bin =
                   new ByteArrayInputStream(bos.toByteArray()); // E
             ois = new ObjectInputStream(bin);                  // F
             // return the new object
             return ois.readObject(); // G
          catch(Exception e)
             System.out.println("Exception in ObjectCloner = " + e);
             throw(e);
          finally
             if(oos != null)
               oos.close();
            if(ois != null)
             ois.close();
    }Enjoy coding in Java. Java never sucks.

  • How to copy a future object in java ???

    here is a part of class Hand for a blackjack game.
    I want to make a copy of a future Hand object using constructor copyHand(),
    I dont know how ????????
    I appreciate anyones help .....
    // the array of cards in the hand
        Card [] cards;
         * Builds a Hand with 0 cards in it, but capable of holding
         * max cards.
        public Hand(int max)
            cards = new Card[max];
         * Builds a copy of this Hand.
         * @return a deep copy of this Hand.
        public Hand copyHand()
        }-med

    Assuming that you DO want a deep copy, begin with a constructor that takes another hand.
    public Hand( Hand h ) { ...Then for each instance variable, within that constructor:
    this.instVar0 = h.instVar0;
    this.instVar1 = h.instVar1;
    . . .And last, for every reference, make sure there is a constructor (or copy method for arrays) that itself makes a deep copy:
    this.ref0 = new Ref0Type( h.ref0 );

  • Deep and Shallow array copy  again

    I am a Computer Analyst and a Java tutor.
    I am trying to understand the terms Shallow and Deep copy
    for arrays, using an example.
    Can you please tell me if my shallow and deep copy below is correct?
    Does the shallow copy not need any memory allocation?
    public Security( int paramAccountNumbers[], String paramPasswords[] ){
    String passwords[];
    int accountNumbers[];
    // INT ARRAY SHALLOW COPY
    accountNumbers = paramAccountNumbers;
    // STRING ARRAY DEEP COPY
    passwords = new String[paramPasswords.length];
    for( int i=0; i<paramPasswords.length; i++ ){
    passwords[i] = paramPasswords;

    You should use clone to copy arrays that contain only references to immutable objects or primitives.
    // "shallow" copy
    final String[] orig = new String[] {"a", "b", "c"};       
    final String[] copy = orig.clone();
    // or java 6 "shallow" copy
    final String[] orig = new String[] {"a", "b", "c"}; 
    final String[] copy = Arrays.copyOf(orig, orig.length, String[].class);If the array contains references to mutable objects you need to clone each element in the array
    // "deep" copy
    final Date[] orig = new Date[] {new Date()};
    final Date[] copy = new Date[orig.length];       
    for (int i = 0; i < orig.length; i++) copy[i] = (Date) orig.clone();However even this may not be sufficient in some cases, which is why cloning is a bit of a minefield.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to properly copy and object

    I have an object that I want to keep immutable, I want to provide a copy() method so that it returns a new instance of the Object its copying. But I wanted to know, just for clarity sake, if I did this:
    public MyClass copy() {
      MyClass copy = new MyClass();
      copy.byteProperty = this.byteProperty;
      return copy;
    }And please note that byteProperty in this case is a byte[].
    Is the reference to the copy's byteProperty array a copy of the originals or a reference to it?
    I would never ever want the user of my class to be able to change the byteProperty of both the class they copied and the new copy by accident.
    For example, would doing this:
    MyClass orig = new MyClass(someByteArray);
    MyClass copy = orig.copy();
    copy.methodToChangeInternals(); //this could internally change around the byte[]would the call to methodToChangeInternals() change the byte[] in both instances?
    Thanks!

    Encephalopathic wrote:
    better than asking this question: test it out for yourself. You get the answer in several ways, by reading and by doing. There's no doubt in my mind that by doing this, you learn more and have a deeper understanding.You are right, and so I did...
    I learnt what flounder mentioned, so I implemented by copy() method differently. Using the ArrayUtils.clone() method, I made a clone of the internal state, whic worked fine.
    I then read ejp's post, and changed my class to implement Cloneable... and changed the method to clone()
    Thanks for the help guys! Very fast turn around :)

  • Help with a deep copy

    What is the best practice for sending doing a deep copy between two View Controllers in an iPhone app. I've designed an app that sends over arrays of arrays and the deeper items aren't coming over as easily as I thought. Do you explicitly copy? Just alloc placeholders and set them equal? Links to any samples would be greatly appreciated.
    Is it a best practice to avoid that kind of data passing - as being overly complex?
    Background:
    I'm building an iPhone application where I need to send a complex object from one view controller to another - This complex object is an array of arrays of objects.
    I can't just copy a reference to the complex object over to a variable on the receiving view controller, as none of the nested array contents come over.
    So I think I need to do a deep copy - but need advice on best practices for that. The array of arrays contain objects, so ideally, Id just be able to :
    Thanks for any advice!

    There are many ways of solving this.
    One way is to centralize the information:
    You create a singleton class that is the datasource for both view, so you don't need to pass in anything. If you can't do that because the datasources are generally different except for this specific array of arrays, then make the singleton class be the source of that array and nothing else.

Maybe you are looking for

  • How to have custom control in DataGridView display object's value?

    I have a sample project located here The project has a main form `Form1` where the user can enter customers in a datagridview. The `CustomerType` column is a custom control and when the user clicks the button, a search form `Form2` pops up. The searc

  • Error:movement type for follow-on document missing

    Hello, Can anyone help me that i got the error message while creating the shopping cart from INTERNAL GOODS/SERVIES after adding the product id in the second step. Error :"movement type for follow-on document missing"

  • Problem while creating user

    Hi We have installed a SAP Netweaver 2004s system on AIX box. We have installed the J2EE + ABAP Engine. While creating the user from the portal we get the following error: #1.5#1E656000400200710000008E000890AC00042D27C0FEBD4D#1175548671736#com.sap.se

  • Quality of still images in PE9

    Sorry, I know this has been discussed before, but I'm only an occasional amateur videographer, and the terminology in other forum posts is going right over my head.  I've tried, honestly I have!  But it's all too technical. I have PE9. Need to use st

  • I have a very slow startup for a macbook pro after installing Maverick

    I have a very slow startup for a macbook pro after installing Maverick