java方法返回map
时间: 2023-09-29 16:03:57 浏览: 53
当一个Java方法需要返回一个Map类型的值时,你可以在方法签名中指定返回值类型为Map,并在方法体中创建和填充该Map对象。以下是一个示例:
```java
import java.util.HashMap;
import java.util.Map;
public class MyClass {
public static void main(String[] args) {
Map<String, Integer> resultMap = getMap();
System.out.println(resultMap);
}
public static Map<String, Integer> getMap() {
Map<String, Integer> map = new HashMap<>();
map.put("Key1", 1);
map.put("Key2", 2);
map.put("Key3", 3);
return map;
}
}
```
在上面的示例中,`getMap()` 方法返回一个 `Map<String, Integer>` 类型的对象。在方法体内,我们创建了一个 `HashMap` 对象,并使用 `put()` 方法填充了一些键值对。最后,我们将该Map对象返回给调用者。
请注意,你可以根据需要选择不同的`Map`实现类(例如`HashMap`、`TreeMap`等),并根据键值对的类型来指定泛型参数。