Iterable 是序列(Seq), 集(Set) 映射(Map)的特质
序列式有序的集合如数组和列表
集合可以通过== 方法确定对每个对象最多包含一个
映射包含了键值映射关系的集合
列表缓存:
使用ListBuffer代替List 另一个理由是为了避免栈溢出的风险
数组缓存: ArrayBuffer需要先从可变集合包引用 scala.collection.mutable.ArrayBuffer
val buf = new ArrayBuffer[Int]()
队列Queue:先进先出
class BankAccount {
private var bal: Int = 0
def balance: Int = bal
def deposit(account: Int){
require(account > 0)
bal += account
}
def widthDraw(account: Int): Boolean = {
if (account > bal ) false
else {bal -= account
true }
}
}
abstract class Simulation {
type Action = {} => Unit
case class WorkItem(time: Int, action: Action)
private var currtime = 0
def currentTime: Int = currtime private var agenda: List[WorkItem] = List()
private def insert(arg: List[WorkItem],
item: WorkItem) : List[WorkItem] = {
if (arg.isEmpty || item.time < arg.head.time) item :: arg
else arg.head :: insert(arg.tail, item)
}
def afterDelay(delay: Int)(block: => Unit) = {
/* val item = WorkItem(currentTime + delay, { } => block)
agenda = insert(agenda, item )*/
} private def next(){
(agenda: @unchecked) match{
case item:: rest =>
agenda = rest
currtime = item.time
item.action()
}
}
def run(){
afterDelay(0){
println("*** sim start... time = + currentTime +***")
}
// while (!agenda.isEmpty) next()
}
}
class Time {
private[tjis] var h = 12
private[this] var n = {}
def hour: Int = h
def hour_ = (x: Int) {h = x}
def minute: Int = m
def minute_ = (x: Int) {m = x}}
class scala {}
object scala{
def main(args: Array[String]) {
System.out.println("HelloWorld")
}
def isort(sx: List[Int]): List[Int] = {
if (sx.isEmpty) Nil else isinsert(sx.head, isort(sx.tail))
} def isinsert(ss: Int,sx: List[Int]) : List[Int] = {
if (sx.isEmpty || ss <= sx.head) ss :: sx else sx.head :: isinsert(ss, sx.tail)
}
// 以下使用模式匹配
def isort2(sx: List[Int]) : List[Int] = sx match {
case List() => List()
case x :: sxl => insert2(x, isort2(sxl))
} def insert2(x: Int, xs: List[Int]): List[Int] = xs match {
case List() => List(x)
case y :: ys => if (x <= y) x:: xs else y :: insert2(x, ys)
} def append1[T](sx: List[T], ys: List[T]) : List[T] ={
sx match {
case List() => ys
// case x :: sxl => x :: append1(sxl, ys)
}
}
//队列
val queue1 = new mutable.Queue[Int]
val va1 = queue1.enqueue(1) // 不可变队列添加元素用enQueue
val queue = new mutable.Queue[String]
queue += "a"
queue ++= List("b", "c") //有序的
val ts = mutable.TreeSet(2,4,6,7,0,8,3)
def mapMaker: Map[String, String] = {
new HashMap[String, String] with
SynchronizedMap[String, String] {
// override def default1(key: String) = " hellon word"
}
}
}