Chef.Yeon
Code Cook
Chef.Yeon
전체 방문자
오늘
어제
  • 분류 전체보기 (230)
    • 게임 개발 (1)
      • Unity (1)
    • Android (27)
      • Kotlin (19)
      • 우아한테크코스 5기 (4)
    • Language (11)
      • 파이썬 (3)
      • Java (7)
    • DB (2)
      • SQL (16)
    • Spring (25)
    • 코딩테스트 (56)
    • Git (1)
    • TIL (85)
    • DevOps (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 코딩테스트
  • 문자열
  • ec2
  • 파이썬
  • Android
  • Docker
  • 프로그래머스
  • kibana
  • 코틀린 인 액션
  • grafana
  • rsocket
  • Wil
  • 다이나믹 프로그래밍
  • java
  • 안드로이드
  • 내림차순
  • elasticsearch
  • enum
  • kotlin
  • 우아한테크코스
  • webflux
  • MariaDB
  • 프리코스
  • 코틀린
  • 레포지토리
  • spring
  • SQL
  • til
  • 백준
  • 에라토스테네스의 체

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Chef.Yeon

Code Cook

Android/Kotlin

[Kotlin] 클래스 toString/equals/hashCode, data class

2022. 9. 10. 03:28

클래스 - 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
    'Android/Kotlin' 카테고리의 다른 글
    • [Kotlin] List, Set, Map, Collection Operations
    • [Kotlin] Package, 가시성 변경자(public,private,internal,protected)
    • [Kotlin] 함수, Superclass, Subclass
    • [Kotlin] 클래스 상속, 추상화, 인터페이스
    Chef.Yeon
    Chef.Yeon
    보기 좋고 깔끔한 코드를 요리하기 위해 노력하고 있습니다.

    티스토리툴바