2017-07-04 117 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