java 从 hashset 中删除元素会中断 while 循环并留下 nul 错误

java removing element from hashset breaks while loop and leaves nul error

我有一个房间对象的哈希集,这些房间对象是根据用户输入在另一个函数中生成的,并被添加到哈希集中。在这里,我们遍历哈希集中的房间,然后遍历用户并根据房间中的人数增加房间数。这非常有效,除非房间需要 deleted.log.error(ex.getMessage());留下空错误,并且它不会继续遍历其余元素并且 stringbuilder 留空。下一次 sendroomlist 触发虽然它添加了房间和它们的数量到 stringbuilder 但我需要它一次性完成所有这些请任何帮助让我走上正确的轨道

这是我的哈希集

 private Set<Room> rooms = Collections.synchronizedSet(new HashSet<Room>());

如果您需要查看我在哪里将房间添加到房间哈希集 lmk

      private void sendRoomList()
{
    StringBuilder sb = new StringBuilder();
    String strRoom;
    int roomCount = 0;
    int spaghetticount = 0;
   // Room objRoom;
    try
    {
        synchronized (rooms)
        {
  // {
       //     Iterator<Room> iterRoom = rooms.iterator();
         //   while (iterRoom.hasNext())
           // {
   //             Room s = (Room) iterRoom.next();
        //        if ( (s.getName().toString().equalsIgnoreCase(roomName)) )
       // { return true;

       // }
            //Iterator<String> iterRoom = rooms.iterator();
               Iterator<Room> iterRoom = rooms.iterator();

                    while (iterRoom.hasNext())
            {
                //Room s = (Room) iterRoom.next();
                Room objRoom = (Room) iterRoom.next();
                strRoom = (String) objRoom.getName();
                synchronized (sessions)
                {
                    roomCount = 0;
                    Iterator<IoSession> iterSessions = sessions.iterator();

                    while (iterSessions.hasNext())
                    {
                        IoSession s = (IoSession) iterSessions.next();
                        if (s.isConnected())
                        {    
                            if (s.getAttribute("room").toString().equalsIgnoreCase(strRoom))
                            {

                                roomCount++;
                            }
                        }
                    }
                }
                if (roomCount <= 0 && strRoom != defaultRoom)
                {
                  synchronized (rooms)
                    {
                     rooms.remove(objRoom);
                    }
                }
                else
                {
                    sb.append(strRoom + "|" + roomCount + "~");
                }
            }
        }
    }
    catch (Exception ex)
    {
    log.error(ex.getMessage());
    }
    broadcastRoomList(sb.toString());
}

使用 iterRoom.remove() 而不是 rooms.remove(objRoom)。