Risolto In Java, come posso replicare un oggetto?

OliWan

Utente Bronze
15 Luglio 2022
20
15
0
23
Consider the following code:

[ ICODE ]
DummyBean dum = new DummyBean ( );
dum.setDummy ( "foo" );
System.out.println ( dum.getDummy ( ) ); // prints 'foo'

DummyBean dumtwo = dum;
System.out.println ( dumtwo.getDummy ( ) ); // prints 'foo'

dum.setDummy ( "bar" );
System.out.println ( dumtwo.getDummy ( ) ); // prints 'bar' but it should print 'foo'
[ / ICODE ]

So, I want to copy dum to dumtwo and change dum without affecting dumtwo. But the code above doesn't. When I change something in dum, the same change also occurs in dumtwo.

I guess, when I say dumtwo = dum, Java only copies the reference. So, is there a way to create a new copy of dum and assign it to dumtwo?
 
Ultima modifica:
You have created two references pointing to the same object in the Heap, namely "dum" and "dumtwo". If you want to make independent changes to the dumtwo object, you must first create it separately and then assign it, through a set, the property and not the reference of the "dum" object.

You should do something likes this:

Java:
DummyBean dum = new DummyBean();

dum.setName("foo");

DummyBean dumtwo = new DummyBean();

dumtwo.setName(dum.getName()); //You must also create getters for the property you want to change

Eventually this class will look like this:
Java:
package dummybean;

public class DummyBean {

        private String name;

        public String getName() {
                return this.name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public static void main(String[] args) {
                DummyBean dum = new DummyBean();
                DummyBean dum2 = new DummyBean();
                dum.setName("Mario");
                dum2.setName(dum.getName());
                System.out.println(dum2.getName());
                dum.setName("Luigi");
                System.out.println(dum2.getName()); //dum2's name remains the same
        }
}
 
  • Mi piace
Reazioni: OliWan