2011-07-03 22 views
3

我是Java新手,需要知道如何將一個關聯數組(Map)作爲函數中的單個參數傳遞。Java:通過地圖作爲函數參數

下面是我想要在Java中執行的操作,以PHP顯示。

<?php 
public class exampleClass { 
public function exampleFunction($exampleParam){ 
    if(isset($exampleParam['exampleKey'])){ 
    return true; 
    } 
    else { 
    return false; 
    } 
} 
} 
$ourMap = array(
'exampleKey' => "yes, it is set" 
); 
$ourClass = new exampleClass(); 
$ourResult = $ourClass->exampleFunction($ourMap); 
if(!$ourResult){ 
echo "In Map"; 
} 
else { 
echo "Not in Map"; 
} 
?> 

回答

9
public boolean foo(Map<K,V> map) { 
    ... 
} 

K是鍵的類型,以及V是值的類型。

注意Map只是一個接口,使創建這樣的地圖,你需要創建的HashMap或類似的實例,就像這樣:

Map<K,V> map = new HashMap<K, V>(); 
foo(map); 

參見:

4
public class ExampleClass { 
    public boolean exampleFunction(Map<String,String> exampleParam) { 
    return exampleParam.containsKey("exampleKey"); 
    } 

    public static void main(String[] args) { 
    Map<String,String> ourMap = new HashMap<String,String>(); 
    ourMap.put("exampleKey", "yes, it is set"); 
    ExampleClass ourObject = new ExampleClass(); 
    boolean ourResult = ourObject.exampleFunction(ourMap); 
    System.out.print(ourResult ? "In Map" : "Not in Map"); 
    } 
} 

正如你所看到的,只需使用Map