首页 > 代码库 > scala容器使用

scala容器使用

花了两个小时左右,学习了一下scala语言, 由于scala运行在jvm之上, 可以使用java容器也可以使用scala自带的容器.

import java.utilimport java.util.{HashMap => JavaHashMap}import scala.collection.mutable.HashMapimport java.util.{ArrayList => JavaList} // renameobject tewst {   def testarry(): Unit = {     print("scala array")     val buf = new scala.collection.mutable.ArrayBuffer[Int]     for (i <- 0 to 10) {       buf += i     }     buf += 11     buf.foreach(u =>print(u + "\t"))     // 数组     print("\n java array \n")     var arry = new Array[String](3);     arry(0) = "javaarray0";     arry(1) = "javaarray1";     arry(2) = "javaarray2";     for(i <- 0 to 2){       print(arry(i) + "\t");     }   }   def testlist(): Unit ={     print("\n scala list \n")     // 效果一样     // var buf = new scala.collection.mutable.ListBuffer[Int]     var buf = scala.collection.mutable.ListBuffer.empty[Int]     for(i <- 0 to 10)       buf += i     buf.foreach(B=>print(B + "\t"))     print("\n java list \n")     var javalist = new JavaList[Int]()     for(i <- 0 to 10){       javalist.add(i)     }     for(i <- 0 to javalist.size() - 1)       print(javalist.get(i) + "\t")   }  def testlistcombine(): Unit ={    var list1 = List("list1", "list2", "list3");    list1.foreach(list=>print("合并前: " +  list + "\n"))    var list2 = List("list11", "list12", "list13");    list2.foreach(list=>print("合并前: " + list + "\n"))    var list3 = list1 :::list2    list3.foreach(list=>print("合并后: " + list + "\n"))  }  def testset(): Unit ={    print("\n scala set \n")    var set =  scala.collection.mutable.HashSet("set1", "set2")    set += "set3"    set.foreach(value=http://www.mamicode.com/>print(value +"\t"))    print("\n java set \n")    var javaset = new util.HashSet[String]()    for(i <- 0 to 3){      javaset.add("set" + i.toString())    }    var itor = javaset.iterator()    while(itor.hasNext){      print(itor.next()  +  " \t")    }  }   def testhashmap(): Unit ={     print("\n scala hashmap \n")     var buf = new scala.collection.mutable.HashMap[Int, Int]()     for (i <- 0 to 10){       buf += (i -> i)     }     buf += (11 -> 11)     buf.foreach(f=>print("key: " + f._1 + "value :" + f._2 + "\t"))     print("\n java hashmap \n")     var javamap  = new JavaHashMap[String, String]()     for(i <- 0 to 10){       javamap.put(i.toString, i.toString)     }     for(i <- javamap.keySet().toArray()){       print("key:= " + i  + " value " + javamap.get(i) + "\t")     }   }   def main(args: Array[String]) {     testarry()     testlist()     testset()     testhashmap()  }}

  

scala容器使用