Created files for deep and shallow copy in java
This commit is contained in:
parent
fe5fd5004c
commit
2315b0cb79
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.objectcopy;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
|
||||||
|
class DeepCopyPerson implements Serializable {
|
||||||
|
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public DeepCopyPerson(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DeepCopyPerson deepCopy(DeepCopyPerson person) throws IOException, ClassNotFoundException {
|
||||||
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||||
|
ObjectOutputStream out = new ObjectOutputStream(bos);
|
||||||
|
out.writeObject(person);
|
||||||
|
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
|
||||||
|
ObjectInputStream in = new ObjectInputStream(bis);
|
||||||
|
|
||||||
|
return (DeepCopyPerson) in.readObject();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
package com.baeldung.objectcopy;
|
||||||
|
|
||||||
|
class ShallowCopyPerson {
|
||||||
|
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public ShallowCopyPerson(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.objectcopy;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class DeepCopyPersonUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPerson_whenDeepCopy_thenIndependentCopy() throws IOException, ClassNotFoundException {
|
||||||
|
DeepCopyPerson person1 = new DeepCopyPerson(30);
|
||||||
|
DeepCopyPerson person2 = DeepCopyPerson.deepCopy(person1);
|
||||||
|
person1.age = 25;
|
||||||
|
|
||||||
|
assertEquals(30, person2.age);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.objectcopy;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class ShallowCopyPersonUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPerson_whenShallowCopy_thenSharedReference() {
|
||||||
|
ShallowCopyPerson person1 = new ShallowCopyPerson(30);
|
||||||
|
ShallowCopyPerson person2 = person1;
|
||||||
|
person1.age = 25;
|
||||||
|
|
||||||
|
assertEquals(25, person2.age);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue