클래스 - toString
val product = Product("패션", "운동화")
println("$product") // Product@60addb54 -> 인스턴스 정보를 얻는데 도움X
class Product(val categoryLabel: String, val name: String=""){
override fun toString(): String {
return "Product(categoryLabel=$categoryLabel, name=$name)"
}
}
클래스 - equals
val prodcut1 = Product("패션", "운동화")
val prodcut1 = Product("패션", "운동화")
println(product1 == product2) // false
- 같은 정보를 담고 있다면 true를 출력하도록 equals 오버라이딩 후 출력하면 true
class Product(val categoryLabel: String, val name: String=""){
override fun equals(otehr: Any?): Boolean {
if(other == null || other !is Product) return false
return categoryLabel == oother.categoryLabel && name == other.name
}
}
클래스 - hashCode
- 해시 함수 : 임의의 길이의 데이터를 고정된 길이의 데이터로 매핑하는 함수
- 해시 값, 해시 코드, 해시 체크섬, 해시 : 해시 함수로 얻어지는 값
- 객체의 해시코드 비교 후, 해시 코드가 같은 경우에만 실제 값 비교
val prodcut1 = Product("패션", "운동화")
val prodcut1 = Product("패션", "운동화")
val productSet = hashSetOf(product1)
println(productSet.contains(product2)) // false
- productSet은 hashSet 타입 -> unique 원소를 갖는 자료구조
HashSet
- hashCode를 고유한 식별자로 사용해 검색 최적화
- 객체의 hashCode 비교 후, 해시 코드가 같은 경우에만 실제 값 비교
class Product(val categoryLabel: String, val name: String=""{
override fun hashCode(): Int {
return categoryLabel.hashCode() + name.hashCode()
}
}
클래스 - toString, equals, hashCode
class Product(val categoryLabel: String, val name: String=""){
override fun toString(): String {
return "Product(categoryLabel=$categoryLabel, name=$name)"
}
override fun equals(otehr: Any?): Boolean {
if(other == null || other !is Product) return false
return categoryLabel == oother.categoryLabel && name == other.name
}
override fun hashCode(): Int {
return categoryLabel.hashCode() + name.hashCode()
}
}
data class
- 클래스 앞에 data 키워드 추가
- 위와 같은 오버라이딩 과정을 대신해줌
- 데이터를 저장할 때 toString, equals, hashCode를 override 할 필요가 없음
data class - copy
- 동일한 값을 가진 프로퍼티는 유지한 채, 지정한 값만 변경
- 원본 객체에 영향을 주지 않음 (새로운 객체 생성)
val earring = Product("패션", "귀걸이")
val ring = acc.copy(name="반지")
728x90
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] List, Set, Map, Collection Operations (0) | 2022.09.16 |
---|---|
[Kotlin] Package, 가시성 변경자(public,private,internal,protected) (0) | 2022.09.11 |
[Kotlin] 함수, Superclass, Subclass (0) | 2022.09.10 |
[Kotlin] 클래스 상속, 추상화, 인터페이스 (0) | 2022.09.09 |
[Kotlin] Operator, conditions & loop (0) | 2022.09.06 |