2014年02月25日 星期二 09:39
Map与我们在上一篇文章学习到的Set容器类似,主要区别是Map的元素包括Key和Value两部分,并且Key和Value可以使任意数据类型。
Maps let you associate a value with each element of the collection. Using a map looks similar to using an array, except that instead of indexing with integers counting from 0, you can use any kind of key.
Scala中的Map提供了一些不太寻常的操作符API,比如我们可以使用+操作符来增加元素,可以使用-操作符来删除元素,还可以使用++运算符来一次性增加多个元素。当然,它也提供了method风格的的API来实现同样的功能,比如put和remove。
代码示例如下:
import scala.collection.mutable.HashMap;
object S009_Maps {
def main(args: Array[String]): Unit = {
val friends=HashMap[String,String]();
friends += ("mengguang" -> "mengguang@gmail.com");
friends += ("mengkang" -> "mengkang@163.com");
friends.put("menghui", "menghui@126.com")
for(friend <- friends){
print(friend._1);
print(" => ");
println(friend._2);
}
println("--------------")
friends.remove("mengkang")
for((name,email) <- friends){
println(name + " => " + email)
}
}
}
参考资料:
http://www.artima.com/pins1ed/collections.html
Zeuux © 2025
京ICP备05028076号