我正在尝试编写一些代码,根据是否成功从 HashMap 中删除项目来返回 boolean 值。
我的理解是,map.remove(Key) 如果有效则应返回 Key,如果无效则应返回 null。我的方法是检查返回值是否为 null,如果是则打印 false,如果有其他值则打印 true。
我遇到的问题是我不知道如何检查我的方法内的返回值。
这是我迄今为止的尝试。
public boolean deleteMapEntry(String entry)
{
testMap.remove(entry);
if(null)
{
return false;
}
else
{
return true;
}
}
显然说 if (null) 不起作用,但我找不到什么能起作用。
最佳答案
您需要将testMap.remove(entry)
的值分配给一个变量来测试它是否为空...
String value = testMap.remove(entry);
return value != null;
您也可以直接测试删除的内容,而不使用变量:
return testMap.remove(entry) != null;
关于java - 检查 if 语句的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986228/