您当前的位置: 首页 >  scala

宝哥大数据

暂无认证

  • 2浏览

    0关注

    1029博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

scala 中的equal问题(未解决)

宝哥大数据 发布时间:2019-06-24 21:11:42 ,浏览量:2

class ReportKey extends Serializable {
    private var date: String = null
    private var area: Short = 0
    private var province: Short = 0
    private var city: Short = 0
    private var maincate = ""
    private var ecuType: String = ""
    
    def this(date: String, area: Short, province: Short, city: Short, maincate: String) {
        this()
        this.date = date
        this.area = area
        this.province = province
        this.city = city
        this.maincate = maincate
    }

    def this(date: String, area: Short, province: Short, city: Short, maincate: String, ecuType: String) {
        this()
        this.date = date
        this.area = area
        this.province = province
        this.city = city
        this.maincate = maincate
        this.ecuType = ecuType
    }

 	// getter setter ...

    def canEqual(other: Any): Boolean = other.isInstanceOf[ReportKey]

    override def equals(other: Any): Boolean = other match {
        case that: ReportKey =>
            println("sdfsdfsdfsf..." + (area == that.getArea())) 
            (that canEqual this) &&
                date != null && date.equals(that.getDate()) &&
                area == that.getArea() &&
                province == that.getProvince() &&
                city == that.getProvince() &&
                maincate != null && maincate.equals(that.getMaincate())
                ecuType != null && ecuType.equals(that.getEcuType())
        case _ => println("uuuuuuuu")
            false

    }

    override def hashCode(): Int = {
        val state = Seq(date, area, province, city, maincate, ecuType)
        state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
    }
}

测试是否相等

object T {
    def main(args: Array[String]): Unit = {
        val a = new ReportKey()
        a.setArea(6)
        a.setProvince(43)
        a.setCity(345)
        a.setDate("2018-12-03")
        a.setMaincate("U1")
        a.setEcuType("v2")

        val b = new ReportKey()
        b.setArea(2)
        b.setProvince(21)
        b.setCity(103)
        b.setDate("2018-12-03")
        b.setMaincate("N1S")
        b.setEcuType("v2")

        println(a.getArea() == b.getArea())
        println(a)
        println(b)
        println("a.equal(b): " + a.equals(b))
        println("a == b: " + (a == b))
        println((a.hashCode() == b.hashCode()) + " 是否相等。。。")
}
诡异: 本来已经判断area不相等sdfsdfsdfsf...false, equal() 和==都应该是false, 但是结果得到是true。

在这里插入图片描述

暂时的解决方法: 将equals()和hashCode()都删除, 然后自动生成。
关注
打赏
1587549273
查看更多评论
立即登录/注册

微信扫码登录

0.0411s