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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:22:58  来源:igfitidea点击:

Java: Passing a Map as a function parameter

javaphparraysfunctionmap

提问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 Kis the type of the keys, and Vis the type of the values.

其中K是键V的类型, 是值的类型。

Note that Mapis only an interface, so to create such a map, you'll need to create an instance of HashMapor 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