我正在尝试执行这个功能
import java.util.Map;
public class MyClass {
public static Map<String, Integer> runQuery(Integer x,Integer y){
Map<String, Integer> map = Map<String, Integer> () ;
map.put("key1", x);
map.put("key2", y);
return map;
}
public void main(String args[]) {
int x=10;
int y=25;
int z=x+y;
Map<String, Integer> result = runQuery(3, 4);
System.out.println("Sum of x+y = " + z);
System.out.println("first val = " + result.get("key1"));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误:
/MyClass.java:7: error: ';' expected
Map<String, Integer> map = Map<String, Integer> () ;
Run Code Online (Sandbox Code Playgroud)
我指的是这个答案: 为什么我的 Java 代码出现编译错误“;预期”? 似乎提到该方法应该在主方法之外,这就是我的代码中的情况,我不知道我错过了什么?
这里有两个问题:
Map是一个接口,因此您无法创建它的实例。您需要指定具体类型。new用于调用构造函数的部分。它应该是:
Map<String, Integer> map = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)
...或使用类型推断:
Map<String, Integer> map = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
java.util.HashMap(当然,您需要 import ,或者您可以使用不同的地图实现。)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |