首页 > 解决方案 > 获取哈希图

问题描述

获取哈希图问题。

我试着去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 有人可以向我解释一下吗?

标签: javahashmap

解决方案


编码

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 代码约定


推荐阅读