- //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
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |