Java:将地图作为函数参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6562892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Passing a Map as a function parameter
提问by TeamBlast
I'm new to Java, and need to know how to pass an associative array (Map) as a single parameter in a function.
我是 Java 新手,需要知道如何在函数中将关联数组 (Map) 作为单个参数传递。
Here's what I'm wanting to do in Java, shown in PHP.
这是我想要在 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";
}
?>
回答by Sebastian Paaske T?rholm
public boolean foo(Map<K,V> map) {
...
}
Where K
is the type of the keys, and V
is the type of the values.
其中K
是键V
的类型, 是值的类型。
Note that Map
is only an interface, so to create such a map, you'll need to create an instance of HashMap
or similar, like so:
请注意,这Map
只是一个界面,因此要创建这样的地图,您需要创建一个HashMap
或类似的实例,如下所示:
Map<K,V> map = new HashMap<K, V>();
foo(map);
See also:
也可以看看:
回答by phihag
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");
}
}
As you can see, just use a Map.
如您所见,只需使用Map。