<Object 클래스의 대표 메서드 및 프로퍼티>
- toString() : 문자열 표현을 얻음
- operator == : 비교
- hashCode : 해시값을 얻음
class Book implements Comparable<Book> {
String title;
String comment;
String publishDate;
Book({
required this.title,
required this.comment,
publishDate,
}) : publishDate = DateFormat('yyyy-MM-dd').format(publishDate);
Book copyWith({
String? title,
String? comment,
String? publishDate,
}) {
return Book(
title: title ?? this.title,
comment: comment ?? this.comment,
publishDate: publishDate ?? this.publishDate);
}
bool operator ==(Object other) =>
identical(this, other) ||
other is Book &&
runtimeType == other.runtimeType &&
title == other.title &&
publishDate == other.publishDate;
int get hashCode => title.hashCode ^ publishDate.hashCode;
int compareTo(Book other) {
return publishDate.compareTo(other.publishDate);
}
String toString() {
return 'Book{title: $title, comment: $comment, publishDate: $publishDate}';
}
}
오버라이드 하여, 객체의 기본 출력 정보를 수정 할 수 있음.
toString() {
return 'Book{title: $title, comment: $comment, publishDate: $publishDate}';
}
String
== : 참조의 비교
== 연산자를 오버라이드 하여 나만의 동일성 규칙을 변경 할 수 있다.
operator ==(Object other) =>
identical(this, other) ||
other is Book &&
runtimeType == other.runtimeType &&
title == other.title &&
publishDate == other.publishDate;
bool
Set, Map 계열은 요소를 검색할 때 hashCode 를 사용하여 빠르다. List는 순차검색이라 느림
- 모든 객체는 해시값을 가진다
- 동일한 객체는 항상 같은 해시값을 가진다.
Book book1 =
Book(title: 'Flutter', comment: '굿', publishDate: DateTime.now());
print(book1.hashCode);
// 291048910
List.sort() 메서드는 컬렉션 내부를 정렬해 줌
final pocketMon = ['잠만보', '이상해씨', '꼬부기'];
print(pocketMon);
// [잠만보, 이상해씨, 꼬부기]
// 생략시 List Comparable.compare 오름차순 적용
pocketMon.sort();
print(pocketMon);
// [꼬부기, 이상해씨, 잠만보]
// List Comparable.compare 오름차순 ( 기본옵션과 같음 )
pocketMon.sort((a, b) => a.compareTo(b));
print(pocketMon);
// [꼬부기, 이상해씨, 잠만보]
// Comparator 조건 재정의 하여 내림차순으로 변경
pocketMon.sort((a, b) => -a.compareTo(b));
print(pocketMon);
// [잠만보, 이상해씨, 꼬부기]
sort() 메서드를 사용하기 위해서는 다음과 같은 제약이 따름
void sort(
[int compare(
E a,
E b
)?]
)
compare
기능에 지정된 순서에 따라 해당 List를 정렬하며,
생략할 경우 List의 기본 Comparable.compare를 사용하고 조건을 커스텀 하여 정렬 조건을 변경 할 수 있다.
또한 객체의 Comparable.compare를 오버라이드 하여 조건을 커스텀 할 수 있다.
class Book implements Comparable<Book> {
...
int compareTo(Book other) {
return publishDate.compareTo(other.publishDate);
}
!!! 참고 : https://api.flutter.dev/flutter/dart-core/List/sort.html
Dart에서는 깊은 복사를 지원하지 않기 때문에,
직접 작성하거나,
Book copyWith({
String? title,
String? comment,
String? publishDate,
}) {
return Book(
title: title ?? this.title,
comment: comment ?? this.comment,
publishDate: publishDate ?? this.publishDate);
}
플러그인이나 라이브러리를 사용 한다.
Book book1 =
Book(title: 'Flutter', comment: '굿', publishDate: DateTime.now());
print(book1.hashCode);
Book book3 = book1.copyWith(
title: 'Flutter 3', comment: '좋습니다.', publishDate: DateTime.now());
print(book3.hashCode);
// 670310400
// 976908584 // 새로운 객체가 생성 됨!?
// copyWith메서드의 return시 Book(....)으로 객체를 생성해서 반환하기 때문에 ( new 생략 )
// 새로운 객체가 생성 됨
return Book(
title: title ?? this.title,
comment: comment ?? this.comment,
publishDate: publishDate ?? this.publishDate);
얕은 복사의 위험성(?)
class Person {
String name = "누보";
}
void main() {
Person a = Person();
print(a.name);
// 누보
// 사람의 시각에서 b = a 로 '복사'하면
// b와 a는 별개라고 생각 하는 경우가 많은데,
// (그냥.. 복사라고 했으니까..)
// 실제로는 a 인스턴스가 메모리에 올라갈 때 발급(?)되는 '주소값'을 b에 옮기는 것이기 때문에,
// b를 수정하면 a(원본)까지 훼손 되는 불상사가 발생하기 때문에 얕은 카피는 함부로 사용 하면 안됨
Person b = a;
b.name = "잠만보";
print(a.name);
// 잠만보
print(b.name);
// 잠만보
}