gpt4 book ai didi

java - 获取 HashMap

转载 作者:行者123 更新时间:2023-12-02 10:15:13 25 4
gpt4 key购买 nike

获取 HashMap 问题。

我尝试在 if (BookValues.containsKey(ID)) 之外获取 hashmap 并且我总是会得到:

java nullpointer exception

这是代码:(假设这已被声明。我使用 Integer,Class 作为我的 HashMap )

    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 ,应将这一行拆开。以下假设您的 map 值是 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)

还可以考虑遵循java code conventions

关于java - 获取 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com