[英]How to check if a method is not null?
Since I am relatively new to programming I don't now how to check if a method is not null.由于我对编程比较陌生,我现在不知道如何检查方法是否不是 null。 In the following code I need to check if the answers.get method is not null, how can I achieve this?在以下代码中,我需要检查 answers.get 方法是否不是 null,我该如何实现?
public class SharedViewModel extends ViewModel {
private HashMap<Integer, MutableLiveData<String>> answers = new HashMap<>();
public MutableLiveData<String> getAnswer(int questionId) {
return answers.get(questionId);
}
public void setAnswer(int questionId, String answer) {
// TODO make sure that answers.get is not null
answers.get(questionId).setValue(answer);
}
}
Just add a null
check on answers.get(questionId)
whenever you are trying to access that Object or manipulate it.每当您尝试访问 Object 或操作它时,只需在answers.get(questionId)
上添加一个null
检查。
public class SharedViewModel extends ViewModel {
public void setAnswer(int questionId, String answer) {
if(answers.get(questionId)!=null){
answers.get(questionId).setValue(answer);
}
}
}
If you are using Java8 and above you can also use如果您使用的是 Java8 及以上版本,您还可以使用
//nonNull will return true if object is not null
if(Objects.nonNull(answers.get(questionId))){
answers.get(questionId).setValue(answer);
}
Just to add to existing answer and for your todo, you may want to use getOrDefault
,只是为了添加到现有答案和您的待办事项中,您可能想要使用getOrDefault
,
answers.getOrDefault(questionId, answer);
Generally you could do this:通常你可以这样做:
if(methodname(args)! =null ) {//statements} ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.