2017-07-04 118 views
3

可有人请给我具体的例子hashMapOf()方法什么时候应该使用它?方法hashMapOf()在科特林

如果我做这样的事情:

val map2 : HashMap<String, String> = hashMapOf() 
    map2["ok"] = "yes" 

这意味着初始化MAP2财产我可以用它。

但是,像在科特林其他方法,例如:

val arr = arrayListOf<String>("1", "2", "3") 

有什么办法,我可以用这个方法像上面?

回答

8

很简单:

val map = hashMapOf("ok" to "yes", "cancel" to "no") 

print(map) // >>> {ok=yes, cancel=no} 

方法hashMapOf返回java.util.HashMap实例与指定的键 - 值对。

Under the hood

/** 
* Creates a tuple of type [Pair] from this and [that]. 
* 
* This can be useful for creating [Map] literals with less noise, for example: 
* @sample samples.collections.Maps.Instantiation.mapFromPairs 
*/ 
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that) 
+0

谢谢,我知道了,引擎盖下是这样一个有用的代码,请还添加了一个链接到该代码的一部分。 – TapanHP

+0

不客气:) –

1

是的,可以。从kotlinlang.org第一个例子:

val map: HashMap<Int, String> = hashMapOf(1 to "x", 2 to "y", -1 to "zz") 
println(map) // {-1=zz, 1=x, 2=y} 
+0

谢谢,我想我需要更多的阅读文档 – TapanHP