一: set对装入的对象进行去重
import scala.collection.mutable
object class22 {
class Book(var id: Int, var name: String) {
override def equals(obj: Any): Boolean = {
val other = obj.asInstanceOf[Book]
other.id == id && other.name == name
}
override def hashCode(): Int = id
}
def main(args: Array[String]): Unit = {
val set1 = scala.collection.mutable.Set(1,2)
set1 += 1
set1 += 1
set1 += 1
set1 += 1
println(set1)
val book1 = new Book(1,"西游记")
val book2 = new Book(1,"西游记")
println(book1 == book2)
}
}
二:case class与普通class的区别
case class: 样板类
- 可以省略 new
- 属性默认是不可变的:val 修饰
- 它会自动去实现toString, equals, hashCode等方法
scala
object class23 {
case class Student(name:String, age:Int)
def main(args: Array[String]): Unit = {
// val st1 = new Student("小花", 18)
val st1 = Student("小花", 18)
val st2 = Student("小花", 18)
// 属性默认是不可变的:val 修饰
// st1.name = "小花"
println(st1)
println(st1 == st2)
}