Created files for deep and shallow copy in java

This commit is contained in:
Imran Alam 2024-01-16 21:02:52 +05:30
parent fe5fd5004c
commit 2315b0cb79
4 changed files with 69 additions and 0 deletions

View File

@ -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();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.objectcopy;
class ShallowCopyPerson {
int age;
public ShallowCopyPerson(int age) {
this.age = age;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}