Kotlin中数据类的等于方法 [英] Equals method for data class in kotlin

查看:181
本文介绍了Kotlin中数据类的等于方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下数据类

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

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

I read that data classes in Kotlin get equals()/hashcode() method for free.

我实例化了两个对象.

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.

But still the following statements return false.

board1 == board2
board1.equals(board2)

推荐答案

在Kotlin data类的相等性检查中,与其他类一样,使用equals(...)对数组进行比较,该比较将比较数组引用而不是内容. 此处对此行为进行了描述:

In Kotlin data classes equality check, arrays, just like other classes, are compared using equals(...), which compares the arrays references, not the content. This behavior is described here:

所以,只要你说

So, whenever you say

  • arr1 == arr2

DataClass(arr1) == DataClass(arr2)

您可以通过equals()(即参照)比较数组.

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

鉴于此,

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可以自动为非数据类生成的代码.

另一种解决方案是使用List<Int>而不是IntArray.列表在结构上进行了比较,因此您无需覆盖任何内容.

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

这篇关于Kotlin中数据类的等于方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆