ListBuffer、ArrayBuffer、Queue、Stack


点击(此处)折叠或打开

  1. def main(args: Array[String]) {
  2.     import scala.collection.mutable.ListBuffer
  3.     val listBuffer = new ListBuffer[Int]
  4.     listBuffer += 1
  5.     listBuffer += 2
  6.     println(listBuffer) //结果:ListBuffer(1, 2)
  7.     
  8.     import scala.collection.mutable.ArrayBuffer
  9.     val arrayBuffer = new ArrayBuffer[Int]()
  10.     arrayBuffer += 1
  11.     arrayBuffer += 2
  12.     println(arrayBuffer) //结果:ArrayBuffer(1, 2)
  13.     
  14.     val empty = Queue[Int]() //不可变Queueimmutable
  15.     val queue1 = empty.enqueue(1) //追加元素之后,产生一个新的Queue
  16.     val queue2 = queue1.enqueue(List(2,3,4,5))
  17.     println(queue2) //结果:Queue(1, 2, 3, 4, 5)
  18.     val (element, left) = queue2.dequeue //将Queue拆分成两部分,第一个元素和剩下的元素
  19.     println(element + " : " + left)  //结果:1 : Queue(2, 3, 4, 5)
  20.     
  21.     import scala.collection.mutable.Queue
  22.     val queue = Queue[String]()
  23.     queue += "a"
  24.     queue ++= List("b", "c")
  25.     println(queue) //结果:Queue(a, b, c)
  26.     println(queue.dequeue) //和不可变Queue的dequeue方法不同,这里返回Queue的第一个元素,并且移除第一个元素
  27.     println(queue) //结果:Queue(b, c)
  28.     
  29.     import scala.collection.mutable.Stack
  30.     val stack = new Stack[Int]
  31.     stack.push(1)
  32.     stack.push(2)
  33.     stack.push(3)
  34.     println(stack.top) //返回栈顶元素,3,但是不会弹出
  35.     println(stack) //结果依然是:Stack(3, 2, 1)
  36.     println(stack.pop) //弹出栈顶元素
  37.     println(stack) //结果:Stack(2, 1)
  38.       
  39.   }

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1966105/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28912557/viewspace-1966105/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值