class Hero extends Character {
Hero(super.name, super.hp);
String toString() {
return 'Hero{}';
}
}
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번
}
operator ==(Object other) =>
identical(this, other) ||
other is Hero && runtimeType == other.runtimeType;
bool
class Person {
String name;
int age;
Person(this.name, this.age);
// 원하는 규칙으로 재정의 가능
int get hashCode => name.hashcode ^ age.hashCode;
}
임의의 길이를 가진 데이터를 입력받아 고정된 길이의 값, 즉 해시값을 출력하는 함수
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
}
Set, Map 계열은 요소를 검색할 때 hashCode를 사용하여 빠르다.
List는 순차검색이라 느리다
final names = ['Seth', 'Kathy', 'Lars'];
names.sort((a, b) => a.compareTo(b));
print(names); // [Kathy, Lars, Seth]
Comparator = int Function(T a, T 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);
실제 값을 새로운 메모리 공간에 복사하는 것
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);
}