在Kotlin data
类等式判断中,数组和其他类一样,使用equals(...)
进行比较,equals(...)
比较数组引用,而不是内容.这种行为被描述为here:
So, whenever you say
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.