scala的set
//Set特点:唯一(元素不相同):无序
//case class:定义一组数据
class Book(var bookName:String,var author:String,var price:Double){
}
object caseclass{
def main(args: Array[String]): Unit = {
//定义一个可变set
val set1 = scala.collection.mutable.Set[Book]()
//向 Set中添加两条一样的数据
val book1 = new Book("西游记","吴承恩",100)
val book2 = new Book("西游记","吴承恩",100)
val book3 = new Book("西游记","吴承恩",100)
//book1 == book2 ?
println(book1 == book2) // true ? false
set1 += book1
set1 += book2
set1 += book3
set1.foreach(s => {
println(s.author)
})
}
}
//Set特点:唯一(元素不相同):无序
//case class:定义一组数据
class Book(var bookName:String,var author:String,var price:Double){
//判断是否相等的逻辑: bookName相等
override def equals(obj:Any):Boolean = {
// println("equals")
// true
val ob = obj.asInstanceOf[Book]
ob.bookName == bookName
}
override def hashCode(): Int = bookName.hashCode()
override def toString: String = s"书名:$bookName \t 作者:$author \t 价格:$price"
}
//1.属性的默认修饰符是val(不可变),说明对象不能改属性
//2.可以省略new
//3.case class 它自动提供:
// equals方法
// headCode方法
case class Student(name:String)
object caseclass{
def main(args: Array[String]): Unit = {
val s1 = Student("小花")
println(s1)
//定义一个可变set
val set1 = scala.collection.mutable.Set[Book]()
//向 Set中添加两条一样的数据
val book1 = new Book("西游记","吴承恩",100)
println(book1)
val book2 = new Book("西游记","吴承恩",100)
val book3 = new Book("西游记","吴承恩",100)
//book1 == book2 ?
println(book1 == book2) // true ? false
set1 += book1
set1 += book2
set1 += book3
set1.foreach(s => {
println(s.author)
})
}
}
"C:\Program Files\Java\jdk-17\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2022.2.2\lib\idea_rt.jar=53933:C:\Program Files\JetBrains\IntelliJ IDEA 2022.2.2\bin" -Dfile.encoding=UTF-8 -classpath "E:\untitled\untitled9\out\production\untitled9;C:\Program Files (x86)\scala\lib\scala-library.jar;C:\Program Files (x86)\scala\lib\scala-reflect.jar" caseclass
Student(小花)
书名:西游记 作者:吴承恩 价格:100.0
true
吴承恩
进程已结束,退出代码0
原文地址:https://blog.csdn.net/2301_81557172/article/details/143745830
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!