Scala学习笔记25【ListBuffer、ArrayBuffer、Queue、Stack常用操作实战】

package com.yl.scala

object Test {
  def main(args: Array[String]){

    //ListBuffer实战
    import scala.collection.mutable.ListBuffer
    val listBuffer = new ListBuffer[Int]
    listBuffer += 1
    listBuffer += 2
    println("listBuffer = " + listBuffer) //listBuffer = ListBuffer(1, 2)

    //ArrayBuffer实战
    import scala.collection.mutable.ArrayBuffer
    val arrayBuffer = new ArrayBuffer[Int]()
    arrayBuffer += 1
    arrayBuffer += 2
    println("arrayBuffer = " + arrayBuffer) //arrayBuffer = ArrayBuffer(1, 2)

    //Queue实战
    import scala.collection.immutable.Queue  //immutable 不可变的
    val empty = Queue[Int]()
    val queue1 = empty.enqueue(1)
    val queue2 = queue1.enqueue(List(1,2,3,4))
    println("queue1 = " + queue1) //queue1 = Queue(1)
    println("queue2 = " + queue2) //queue2 = Queue(1, 1, 2, 3, 4)

    import scala.collection.mutable.Queue  //mutable 可变的
    val queue = scala.collection.mutable.Queue[String]()
    queue += "Scala"
    queue ++= List("Hadoop", "Spark")
    println("queue = " + queue)  //queue = Queue(Scala, Hadoop, Spark)
    println(queue.dequeue()) //返回第一个元素 Scala

    //Stack实战
    import scala.collection.mutable.Stack
    val stack = new Stack[String]()
    stack.push("S")
    stack.push("c")
    stack.push("a")
    stack.push("l")
    stack.push("a")
    println("stack = " + stack)  //stack = Stack(a, l, a, c, S)
    println("stack.top = " + stack.top) //stack.top = a
    println("stack.pop = " + stack.pop) //移除栈顶元素 stack.pop = a
    println("stack.top = " + stack.top) //stack.top = l
  }
}

运行结果:

listBuffer = ListBuffer(1, 2)
arrayBuffer = ArrayBuffer(1, 2)
queue1 = Queue(1)
queue2 = Queue(1, 1, 2, 3, 4)
queue = Queue(Scala, Hadoop, Spark)
Scala
stack = Stack(a, l, a, c, S)
stack.top = a
stack.pop = a
stack.top = l

你可能感兴趣的:(scala,ListBuffer)