java - 获取哈希图
问题描述
获取哈希图问题。
我试着去hashmap
外面if (BookValues.containsKey(ID))
,我总是会得到:
java空指针异常
这是代码:(假设这已被声明。我使用 Integer,Class 作为我的哈希图)
int targetID = BookValues.get(ID).BookID.intValue();
String targetTitle = BookValues.get(ID).Title.toString();
String targetAuthor= BookValues.get(ID).Author.toString();
int targetCopies=BookValues.get(ID).Copies.intValue();
每当我在 contains 键中对其进行编码时,它都可以工作,但是当我在外部进行编码时,它会遇到错误。我想把它放在外面,.containsKey
因为它会使我的代码更长,而且我正在尝试保存 spa 有人可以向我解释一下吗?
解决方案
编码
int targetID = BookValues.get(ID).BookID.intValue();
String targetTitle = BookValues.get(ID).Title.toString();
String targetAuthor= BookValues.get(ID).Author.toString();
int targetCopies=BookValues.get(ID).Copies.intValue();
有很多地方可以抛出异常。
BookValues.get(ID)
null
如果它存在或不存在,会给你这个对象。为了避免可能的情况NullPointerException
,这条线应该被打破。以下假设您的地图的值是BookValue
对象。
BookValue value = BookValues.get(ID);
if (value != null) {
int targetId = value.BookID.intValue();
String targetTitle = value.Title.toString();
String targetAuthor = value.Author.toString();
int copies = value.Copies.intValue();
// rest of code here
} else {
// TODO do something if there's no value in the map for the specified key
}
请注意,通过这种方式,您还可以避免重复.get(ID)
on 。
还要考虑遵循java 代码约定
推荐阅读
- python - 尝试在我的 Col 标题顶部添加另一行以 Wkdys 的名称,并在 b/w 中插入 cols,其中所有 cols 为 8 hrs b/w
- r - 在 map_dfr 中指定路径名
- c++ - 创建 openCL 缓冲区会导致延迟
- apache-spark - Spark SQL 中的相关子查询
- flutter - 如何在颤动中向警报对话框添加选项卡
- ios - 如何使用 iOS 14+ 的 ScrollViewReader 和 iOS 13 的部署目标
- python - Python - 遍历字典列表
- javascript - 如何减少 Javascript 重复
- android - 如何使用 curl 推送通知
- typescript - 编译时检查 typescript 接口是否具有一个或多个属性