码迷,mamicode.com
首页 > 其他好文 > 详细

快学Scala-10--List 和Set

时间:2019-03-10 22:16:56      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:sts   var   静态   amp   tail   不可变   mutable   同名   可变   

1.Scala 的main函数入口

class  App{
  //scala 的类不支持静态化
  def main(args: Array[String]): Unit = {
    println("hello")
  }
}
//class 里面的方法都是非静态的
class  Demo01{
  def hello01(): Unit ={
    println("Hello01")
  }
}
//静态方法都在object里面
object  Demo02{
  def hello02(): Unit ={
    println("hello02")
  }
}

如果想一个类里面既想有静态又想有非静态的方法,那么就要写同名的伴生类,如下:

class Demo01{
    def hello01(){
        println("Hello")
    }
}

object Demo01{
    def hello02(){
        println("World")
    }
}

//编译完成就进入一个类里面了,详细查看Demo01.class 文件  使用命令Javap

2.Scala 的List

ArrayList && LinkList  
默认list 的容量有限,不能随便扩容
如果想扩容:
import  scala.collection.mutable.ListBuffer
var arr = Array(1,2,3,4)   //ArrayList array
var list =List(1,2,3,4)   //LinkList
Result:
arr: Array[Int] = Array(1, 2, 3, 4)
list: List[Int] = List(1, 2, 3, 4)
list.head
list.tail
list= list.head::list.tail
Result:
res0: Int = 1   //头
res1: List[Int] = List(2, 3, 4)  //尾
list: List[Int] = List(1, 2, 3, 4)  //头+ 尾

Demo : 对于list递归求和

var list =List(1,2,3,4)  
def listSum(list:List[Int]): Int ={
  if (list == Nil) 0
  else list.head + listSum(list.tail)
}
listSum(list)
Result: 
10

Demo:使用匹配来递归

var list =List(1,2,3,4)  
def listSum(list:List[Int]): Int ={
  list match{
    case Nil => 0
    case h::t => h+listSum(t)
  }
}
3.Scala的Set
Set 的最大特点是互异性
当然和List一样,Set也不可变,数值和容量都不可变,需要变得话使用如下
import  scala.collection.mutable.HashSet
Demo:数据的切分和封装 从array 到数据对象
val  rawData = Array("1 tom 22","2 lucy 33","3 lilei 44")
val   data2 = rawData.map(_.split(" "))
case class  User(id:Int ,name:String,age:Int)
val users = data2.map( arr => User(arr(0).toInt,arr(1),arr(2).toInt))
----------------------------结果-------------------------------
rawData: Array[String] = Array(1 tom 22, 2 lucy 33, 3 lilei 44)
data2: Array[Array[String]] = Array([Ljava.lang.String;@3fc49813, [Ljava.lang.String;@76e1d751, [Ljava.lang.String;@32cef447)
defined class User
users: Array[User] = Array(User(1,tom,22), User(2,lucy,33), User(3,lilei,44))

 

快学Scala-10--List 和Set

标签:sts   var   静态   amp   tail   不可变   mutable   同名   可变   

原文地址:https://www.cnblogs.com/feixiaobai/p/b5f889ec6c6403feb0fd967dcf0e0774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!