//设置一个Book。有三个属性:书名,作者,价格
class Book(var bookNmame:String,var author:String,var price:Double){}
object demo7 {
def main(args: Array[String]): Unit = {
// val set1 = Set(1,1,2,3,3)
// println(set1)
//创建可变S儿童,添加两本相同的书
val set1 = scala.collection.mutable.Set[Book]()
val book1 = new Book("西游记","吴承恩",100)
val book2 = new Book("西游记","吴承恩",100)
println(book1 == book2)
set1 += book1
set1 += book2
//问题:Set可以把两本相同的书。做去重处理吗?
set1.foreach(s =>{
println(s.author)
})
}
}
//Set:特点去重
//设置一个Book。有三个属性:书名,作者,价格
class Book(var bookName:String,var author:String,var price:Double){
override def equals(obj: Any): Boolean = {
//判断依据是书名相同
val o = obj.asInstanceOf[Book]
o.bookName == bookName
}
override def toString: String = s"书名是:$bookName,作者:$author,价格:$price"
override def hashCode(): Int = bookName.hashCode()
}
//case class 的特点
//1,数据是只读的
//2,可以省略new
//3,它内置实现了一些方法
//equals hashCode ,toString
case class BookCase(bookName:String,author:String,price:Double)
object demo8 {
def main(args: Array[String]): Unit = {
val book1 = new Book("a","a",1)
val book11 = new Book("a","a",1)
val set1 = Set(book1,book11)
println(set1)
val book2 = BookCase("a","a",1)
val book3 = BookCase("a","a",1)
println(book1 == book11)
println(book2 == book3)
println(book1)// println会自动去调用对象的toString方法
println(book2)
}
}
1:case class的定义语法是什么?
case class 类名(属性名:类型,属性名:类型)
2:case class的特点?
它的属性值不能被修改
可以不写new
内置了toString,equals,hashCode特别适用于来定义数据格式