I have the following data class

data class PuzzleBoard(val board: IntArray) {
    val dimension by lazy { Math.sqrt(board.size.toDouble()).toInt() }
}

我读到Kotlin中的数据类GET equals()/hashcode()方法是免费的.

I instantiated two objects.

val board1 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))
val board2 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))

但是,下面的语句仍然返回FALSE.

board1 == board2
board1.equals(board2)

推荐答案

在Kotlin data类等式判断中,数组和其他类一样,使用equals(...)进行比较,equals(...)比较数组引用,而不是内容.这种行为被描述为here:

So, whenever you say

  • arr1 == arr2

  • DataClass(arr1) == DataClass(arr2)

  • ...

you get the arrays compared through equals(), i.e. referentially.

Given that,

val arr1 = intArrayOf(1, 2, 3)
val arr2 = intArrayOf(1, 2, 3)

println(arr1 == arr2) // false is expected here
println(PuzzleBoard(arr1) == PuzzleBoard(arr2)) // false too


To override this and have the arrays compared structurally, you can implement equals(...)+hashCode() in your data class using Arrays.equals(...) and Arrays.hashCode(...):

override fun equals(other: Any?): Boolean{
    if (this === other) return true
    if (other?.javaClass != javaClass) return false

    other as PuzzleBoard

    if (!Arrays.equals(board, other.board)) return false

    return true
}

override fun hashCode(): Int{
    return Arrays.hashCode(board)
}

这段代码是IntelliJ IDEA为非数据类自动生成的代码

Another solution is to use List<Int> instead of IntArray. Lists are compared structurally, so that you won't need to override anything.

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

Kotlin:类型不匹配:推断的类型已运行,但应等待

有没有一种简单的方法来识别物体?

用Quarkus和Reactor重写异步过滤器中的数据流

Kotlin 基于参数类型的返回类型推断

Kotlin 获取继承类的默认 hashCode 实现

有没有什么方法或算法可以在没有存储的情况下生成唯一的随机数?

将 Integer 转换为 Unit 编译成功

如何将glide显示的图像下载到设备存储中.Kotlin

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

Kotlin:如何在活页夹中返回正在运行的服务实例?

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

如何捕获传递给模拟函数的参数并返回它?

应用程序在使用 Google Play 服务时遇到问题

Android Jetpack导航,另一个主机片段中的主机片段

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

Kotlin - computed var 属性的用处?

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte

Android studio,构建kotlin时出现奇怪错误:生成错误代码