判断两个对象是相等的

23 阅读1分钟

两个对象做比较==时,会自动调用equals方法。我们可以重写equals方法,并自己定义两个对象相等的标准。

package t2

object test4 {

  class Student(var name:String, var id:String,var age:Int) {

    override def equals(obj:Any):Boolean={
      println("调用了equals...")

      println(this,obj)

      val other=obj.asInstanceOf[Student]

      this.name==other.name && this.id==other.id

    }

  }
  def main(args: Array[String]): Unit = {
    val stu1 =new Student("小花","2023123",18)
    val stu2 =new Student("小明","1212131",18)
    val stu3 =new Student("小明","1212135",18)
    //目标,判断他们是一个人。使用==来输出的时候,应该是true

    println(stu1==stu2)
    println(stu1==stu3)


  }
}

image.png