I'm new to Java, and need to know how to pass an associative array (Map) as a single parameter in a function.
Here's what I'm wanting to do in Java, shown in PHP.
<?php
public class exampleClass {
public function exampleFunction($exampleParam){
if(isset($exampleParam['exampleKey'])){
retu开发者_如何学JAVArn 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";
}
?>
public boolean foo(Map<K,V> map) {
...
}
Where K
is the type of the keys, and V
is the type of the values.
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<K,V> map = new HashMap<K, V>();
foo(map);
See also:
- Map in the Java 6 documentation
- HashMap in the Java 6 documentation
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.
精彩评论