Scala吧~  - 讨论区

标题:Scala Tutorial 008:Set的使用方法

2014年02月24日 星期一 09:37

Set容器可以容纳一组数据类型相同但值不重复的数据,从实现角度来看,可以分为有序(平衡树等实现方式)和无序(哈希表等方式)的两种类型。

By default when you write "Set" or "Map" you get an immutable object. If you want the mutable variant, you need to do an explicit import. Scala gives you easier access to the immutable variants, as a gentle encouragement to prefer them over their mutable counterparts. The easy access is provided via the Predef object, which is implicitly imported into every Scala source file.

在Scala中,默认引入的Set都是Immutable模式,如果需要mutable形式的Set,那么需要显示的引入import scala.collection.mutable.HashSet 或者 import scala.collection.mutable.Set。

编程示例如下:

import scala.collection.mutable.HashSet;

object S008_Sets {

  def main(args: Array[String]): Unit = {
    var friends=Set("mengkang","menghui");
    friends += "mengguang";
    println(friends.contains("mengguang"))
    for(friend <- friends){
      println(friend + ",");
    }
    println()
    val hfriends=HashSet("mengkang","menghui");
    hfriends += "laozhang";
    for(friend <- hfriends){
      println(friend+ ",");
    }
    println
  }

}

参考资料:

http://www.artima.com/pins1ed/collections.html

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号