gpt4 book ai didi

java - 我可以有一个没有键的非空 HashMap 吗?

转载 作者:行者123 更新时间:2023-12-01 23:59:25 25 4
gpt4 key购买 nike

我在 java HashMap 上(仅用于测试的部分代码)出现了奇怪且意外的行为。

为了在将对象存储在 session 中之前尝试为其设置唯一 ID,我使用 if{}else{}声明,但我发现自己的应用程序出现错误。

生成ID是为了测试目的,因为目前没有数据库来实际存储数据,同时存储在 session 中。

这是我的代码片段:

 ...
HttpSession session = request.getSession();
Map<Integer, Booking> bookings = (HashMap<Integer, Booking>) session.getAttribute(SESSION_BOOKINGS);

// Generates ID
if (bookings == null)
{
bookings= new HashMap<Integer, Booking>();
identificator = 1;
}
else
{
Object[] arrayKeys = (Object[]) bookings.keySet().toArray();
Arrays.sort(arrayKeys);
identificator = (Integer) arrayKeys[arrayKeys.length - 1] + 1;
}

...
//... The rest is setting the ID to the current worked on booking,
//... putting the ID/booking pair in the bookings map
//... and storing the map in session, which worked fine

本地图仅包含一个预订时,删除 map 中的预订后会出现错误。之后当我尝试再次注册时,出现错误,错误原因如下 java.lang.ArrayIndexOutOfBoundsException: -1跟踪链接到我的 else 的最后一行声明:identificator = (Integer) arrayKeys[arrayKeys.length - 1] + 1;

所以:

  1. arrayKeys.length -1 == -1 // true
  2. 这意味着 arrayKeys.length == 0 // true
  3. 这又意味着 keySet()来自Map<Integer,Booking> bookings为空

  4. 但测试未进入if声明

另一方面,在一个全新的 session 中(重新启动浏览器或注销并再次登录后),测试确实按预期输入了 if 语句。

测试后我将我的条件从 (bookings==null) 更改为
(bookings==null || bookings.isEmpty()) .
进一步测试表明仅使用 (bookings.isEmpty()在新 session 中注册预订时会导致 NPE。

所以我想知道 Map 是否有可能是非 null 且没有任何值(显然,是的,但我也在问自己如何)以及为什么它之后没有返回 null完全被清空了?

虽然我知道在 new 之后它是空的语句怎么会在 session.getAttribute() 之后称呼 ?这似乎很明显,因为 session 中还没有存储 Map,但同时它看起来很奇怪,因为没有 new声明。

最佳答案

如果

    if (bookings == null)

确实如此,但您没有 map (这与空 map 不同)。

如果执行了else block ,则表示引用了 map 。您对 map 中元素的数量一无所知。您可能想要这样的东西:

if (bookings == null)
{
bookings= new HashMap<Integer, Booking>();
identificator = 1;
} else if (bookings.isEmpty())
{
identificator = 1;
}
else
{
identificator = Collections.max(bookings.keySet()) + 1;
}

回答这个问题:

how come it didn't return to null after it was completely emptied ?

看看这段代码:

Map<Integer, Booking> map = new HashMap<>();

我从未在 map 中输入任何键/值对,因此它是空的。这与我将一些键/值对放入其中然后再次删除它们的状态相同。 map 是空的,但没有理由让它为 null。如果它是 null 我们以后就无法再添加任何内容。

关于java - 我可以有一个没有键的非空 HashMap 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15109034/

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