In Java, the concepts of shallow copy and deep copy are related to copying objects. Let's understand the differences between them and provide examples for both.
Shallow Copy
A shallow copy creates a new object, but instead of copying the content of the object deeply, it copies the references to the objects. As a result, changes made to the objects inside the copy will affect the original object, and vice versa.
import java.util.ArrayList;
import java.util.List;
class Person {
String name;
Person(String name) {
this.name = name;
}
}
public class ShallowCopyExample {
public static void main(String[] args) {
List<Person> originalList = new ArrayList<>();
originalList.add(new Person("Alice"));
originalList.add(new Person("Bob"));
// Shallow copy
List<Person> shallowCopy = new ArrayList<>(originalList);
// Modify the copied object
shallowCopy.get(0).name = "Charlie";
// Changes are reflected in the original list
System.out.println(originalList.get(0).name); // Output: Charlie
}
}
Deep Copy
A deep copy creates a new object and recursively copies all objects referenced by the original object. Changes made to the objects inside the copy do not affect the original object, and vice versa.
import java.util.ArrayList;
import java.util.List;
class Person {
String name;
Person(String name) {
this.name = name;
}
// Deep copy constructor
Person(Person other) {
this.name = other.name;
}
}
public class DeepCopyExample {
public static void main(String[] args) {
List<Person> originalList = new ArrayList<>();
originalList.add(new Person("Alice"));
originalList.add(new Person("Bob"));
// Deep copy
List<Person> deepCopy = new ArrayList<>();
for (Person person : originalList) {
deepCopy.add(new Person(person));
}
// Modify the copied object
deepCopy.get(0).name = "Charlie";
// Changes do not affect the original list
System.out.println(originalList.get(0).name); // Output: Alice
}
}
In the deep copy example, a copy constructor is used in the "Person" class to create a new "Person" object with the same properties. This ensures that the "deepCopy" is truly independent of the "originalList".
Nenhum comentário:
Postar um comentário