我正在尝试使用 Hashmap get() 返回类数据类型,但给我错误说"must return value of type".请告知



方法getVal的返回值报告错误:

必须返回类型为test1的值。

我不确定它为什么会抱怨返回类型,因为我认为get会给你相应键的值。请帮我理解这个逻辑。

public class test1 {
//There is some class named test1
public test1() { //Default Constructor
}
public test1 getVal(String name) {
return sample.get(name);
}
}
public class test {
public test() {
HashMap<String, test1> sample = new Hashmap<>();
sample.put("Name", new test1());
}
}

名为sample的HashMap在getVal方法中不可见。您可以将其作为参数添加到该方法中,或者使HashMapsamplegetVal方法可见。

相关内容

最新更新