自学内容网 自学内容网

scala中的case class

package test_27
//Set的特点:唯一(元素不同);无序
//case class定义一组数据
case 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)
     println(book1==book2)
     set1+=book1
    set1+=book2
    set1+=book3
    set1.foreach(s=>{
      println(s.author)
    })

  }

}

 去掉case还能否去重?

package test_27
//Set的特点:唯一(元素不同);无序
//case class定义一组数据
//case class Book(var bookName:String,var author:String,var price:Double){
//
//}
 class Book(var bookName:String,var author:String,var price:Double){
  //判断是否相等的逻辑bookName相等
  override def equals(obj: Any): Boolean = {
//    println("equal")
//   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方法
//hashCode方法
//toString方法
case class Student( name:String)
object caseclass {
  def main(args: Array[String]): Unit = {
    val s1=new Student("小花")
println(s1)
    //定义一个可变set
   val set1=scala.collection.mutable.Set[Book]()
    //向Set中添加两条一样的数据
    val book1=new Book("西游记","吴承恩",100)
    val book2=new Book("西游记","吴承恩",100)
     val book3=new Book("西游记","吴承恩",100)
     println(book1==book2)
     set1+=book1
    set1+=book2
    set1+=book3
    set1.foreach(s=>{
      println(s.author)
    })

  }

}

 


原文地址:https://blog.csdn.net/zxfgdjfjfjflfllf/article/details/143745470

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!