快学Scala 第十三课 (类型层级,对象相等性)

mac2022-06-30  91

Scala 类型层级:

对象相等性:

和Java一样要重写equals方法和hashcode方法

class Student(val id: Int, val name: String) { override def equals(other: Any) = { val that = other.asInstanceOf[Student] if (that == null) false else id == that.id && name == that.name } override def hashCode = 13 * id.hashCode() + 17 * name.hashCode() } object TestCase { def main(args: Array[String]): Unit = { val s1 = new Student(1,"Sky") val s2 = new Student(1,"Sky") println(s1.equals(s2)) println(s1 == (s2)) } }

返回结果:

true

true

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7352474.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)