개발을 하다 보면 변수를 copy 할 일이 생긴다. 그런데 오랜만에 copy를 사용할 일이 생겨 사용을 하다 보니 shallow copy와 deep copy에 대해 까먹고 개발을 하다가 다시 공부하게 되었다. 그래서 Shallow, Deep Copy에 대해 정리해보려고 한다.
Shallow Copy
class Person {
String? name;
int? age;
Person(this.name, this.age);
}
void main() {
Person personA = Person('사람A',20); // instance 생성
// 본인은 여기서 deep copy가 될 것이라고 생각하고 코드를 작성했었다.
Person personB = personA; // personB 에 personA의 instance가 shallow copy 된다.
personA.name = '김뚜뚜'; // personA의 name값을 변경했다.
// shallow,deep copy 개념이 없다면 personB의 name의 값은 "사람A"라고 생각할 수 있다.
print(personB.name); // 김뚜뚜
// personA와 personB는 동일한 hashCode를 가진다.
print('personA : ${personA.hashCode}');
print('personB : ${personB.hashCode}');
}
Deep Copy
class Person {
String? name;
int? age;
Person(this.name, this.age);
factory Person.clone(Person person) {
return Person(person.name, person.age);
}
}
void main() {
Person personA = Person('사람A', 20); // instance 생성
Person personB = Person.clone(personA); // deep copy
// personA의 name을 변경하였는데
// shallow copy에서 처럼 personB의 name도 바뀌는지를 생각하면서 봐야한다.
personA.name = '김뚜뚜';
print(personB.name);
// 서로다른 hashCode 를 가진것을 확인할 수 있다.
print('personA : ${personA.hashCode}');
print('personB : ${personB.hashCode}');
}
위에서는 class 단일 객체에 대한 copy를 공부했다면 이번에는 컬렉션 중에서 List 타입의 copy를 알아볼 것이다.
Shallow Copy
class Person {
String? name;
int? age;
Person(this.name, this.age);
}
void main() {
List<Person> groupA = [
Person('사람A', 20),
Person('사람B', 30),
];
List<Person> groupB = groupA; // shallow copy
groupB.removeLast(); // groupB의 마지막에 있는 instance 삭제
// copy의 차이를 모른다면 groupB 에만 마지막 instance 만 삭제
// 된것으로 인지하고 있을지도 모른다.
groupA.forEach((e) => print(e.name));
// 두 List의 hashCode 는 동일하다
print('groupA : ${groupA.hashCode}');
print('groupB : ${groupB.hashCode}');
}
Deep Copy
13줄 코드만 변경하고 나머지 코드는 변경하지 않았다.
class Person {
String? name;
int? age;
Person(this.name, this.age);
}
void main() {
List<Person> groupA = [
Person('사람A', 20),
Person('사람B', 30),
];
List<Person> groupB = groupA.toList(); // deep copy
groupB.removeLast(); // groupB의 마지막에 있는 instance 삭제
groupA.forEach((e) => print(e.name));
// hashCode 가 다른것을 확인할 수 있다
print('groupA : ${groupA.hashCode}');
print('groupB : ${groupB.hashCode}');
}
Reference
https://suragch.medium.com/cloning-lists-maps-and-sets-in-dart-d0fc3d6a570a
'Flutter > Document' 카테고리의 다른 글
Flutter Web App 개발 하면서 느낀 문제점 (18) | 2022.08.25 |
---|---|
Android Studio Emulator 창모드로 변경 또는 해제 방법 (0) | 2022.05.09 |
Flutter Warning: Mapping new ns - gradle 업데이트 방법 (0) | 2022.05.08 |
iOS Simulator 변경 방법 (0) | 2022.05.08 |
Flutter firebase 수동 추가 문서 (0) | 2022.05.08 |