인스턴스 기본 조작

허준호·2025년 6월 27일
0

dart 언어 공부

목록 보기
7/16
post-thumbnail

Object

  • dart에서 모든 클래스는 Object 클래스를 상속받기에 Object의 메소드와 프로퍼티를 가지고 있다
  • Object 타입 변수에는 모든 인스턴스를 대입할 수 있다

대표 메소드와 프로퍼티

  • toString(): 문자열로 변환
  • operator ==: 비교
  • hashCode: 해시값을 얻음

toString() 사용법

  • 오버라이드하여 원하는 결과를 얻도록 수정가능
class Hero extends Character {
	Hero(super.name, super.hp);
	
	
	String toString() {
		return 'Hero{}';
	}
}

퀴즈1

void main() {
	final List<Hero> heroes = [];
	
	final h1 = Hero('슈퍼맨', 100);
	final h2 = Hero('슈퍼맨', 100);
	
	heroes.add(h1);
	print(heroes.length); // 1번
	
	heroes.remove(h2);
	print(heroes.length); // 2번
}
  • 1번, 2번 둘 다 1이 출력된다
  • h2는 heroes에 추가되지 않았기에 .remove()해도 변경되는 것은 없다
  • Set도 마찬가지

== 연산자 재정의

  • 재정의하여 동등성 규칙을 재정의할 수 있다
  • List에서 동등성 비교시 사용됨

bool operator ==(Object other) =>
	identical(this, other) ||
	other is Hero && runtimeType == other.runtimeType;

hashCode 재정의

  • hashCode를 재정의하면 Set, Map 내부에서의 동등성 비교가 가능하다
class Person {
	String name;
	int age;
	
	Person(this.name, this.age);
	
	 // 원하는 규칙으로 재정의 가능
	int get hashCode => name.hashcode ^ age.hashCode;
}

해시함수

임의의 길이를 가진 데이터를 입력받아 고정된 길이의 값, 즉 해시값을 출력하는 함수

퀴즈2

class Book extends TangibleAsset {
	String isbn;
	
	Book({required super.name, required this.isbn});
	
	
	book operator ==(Object other) =>
		identical(this, other) ||
		other is Book && runtimeType == other.runtimeType
		&& isbn == other.isbn;
}

void main() {
	Book book1 = Book(name: '홍길동전', isbn: 100);
	
	TangibleAsset book2 = Book(name: '홍길동전', isbn: 100);
	
	print(book1 == book2); // true of false
}
  • 정답: true
  • 선언된 타입은 컴파일 단계에서 인식되는 타입일 뿐
  • 실제 생성되는 인스턴스로 비교 ⇒ Book 인스턴스이면서, isbn이 같기 때문에 동등

Set, Map의 동작 원리

Set, Map 계열은 요소를 검색할 때 hashCode를 사용하여 빠르다.

List는 순차검색이라 느리다

  • 모든 객체는 해시값을 가진다
  • 동일한 객체는 항상 같은 해시값을 가진다

리스트 내 요소 정렬

  • List.sort() 메소드는 컬렉션 내부를 정렬해 준다
final names = ['Seth', 'Kathy', 'Lars'];
names.sort((a, b) => a.compareTo(b));

print(names); // [Kathy, Lars, Seth]
  • Dart의 sort()는 원본을 재정렬하여 반환한다
  • 원본을 복사할 때에는 collection 패키지를 사용하는 것을 추천. sorted()

Comparator typedef

Comparator = int Function(T a, T b);

  • a가 b보다 작으면 음수 반환
  • 같으면 0 반환
  • a가 b보다 크면 양수 반환

객체 복사

class Person {
	String name;
	int age;
	
	Person(this.name, this.age);
	
	Person copyWith({String? name, int? age}) {
		return Person(
			name: name ?? this.name,
			age: age ?? this.age
		);
	}
}

얕은 복사

주소 값을 복사. 참조하고 있는 실제 값은 동일

  • 주소 값을 복사하기 때문에 하나를 변경하면 다른 하나도 같이 변경된다
class Address {
	String street;
	
	Address(this.street);
}

class Person {
	final String name;
	final int age;
	final Address address;
	
	Person(this.name, this.age, this.address);
	
	Person shallowCopy() => Person(name, age, address);
}

void main() {
 Person person1 = Person('홍길동', 30, '서울');
 Person person2 = person1.shallowCopy();
 
 print(identical(person1, person2));
 print(person1.address == person2.address);
  • 얕은복사 메서드로 새로운 Person 객체가 생성되었기 때문에
  • person1과 person2는 동일하지 않지만
  • 두 객체의 address는 동일하다

깊은 복사

실제 값을 새로운 메모리 공간에 복사하는 것

  • 새로운 메모리 공간에 복사되었기 때문에 하나를 변경해도 같이 변경되지 않는다
class Address {
	String street;
	
	Address(this.street);
	
	Address deepCopy() => Address(street);
}

class Person {
	final String name;
	final int age;
	final Address address;
	
	Person(this.name, this.age, this.address);
	
	Person deepCopy() => Person(name, age, address.deepCopy);
}

void main() {
 Person person1 = Person('홍길동', 30, '서울');
 Person person2 = person1.deepCopy();
 
 print(identical(person1, person2));
 print(person1.address == person2.address);
}
  • deepCopy() 메소드를 통해 Address 객체도 새로 생성되었으므로
  • person1.address와 person2.address는 다르다

참고

https://zzang9ha.tistory.com/372

profile
후추랑 소금 좋아하는 개발자

0개의 댓글