简体   繁体   English

使用队列时出现java.util.NoSuchElementException

[英]java.util.NoSuchElementException on using queue

I am using an if statement and when it runs it shows the exception java.util.NoSuchElementException 我正在使用if语句,当它运行时会显示异常java.util.NoSuchElementException

The code is shown below 代码如下所示

if (BackgroundService.pendingQueue != null) {
                logger.error("Here is clear step next 2 ");

            BackgroundService.pendingQueue.remove();

            logger.error("Here is clear step next 3 ");
        }       
        logger.info("BackgroundService.pendingQueue="+BackgroundService.pendingQueue.
size());
        if(BackgroundService.pendingQueue.size() == 0){
            BackgroundService.pendingQueue.clear();
        }
        logger.info("BackgroundService.pendingQueue after task done is ="+BackgroundService.pendingQueue.size());
    }

The exeption is show between the "clear step 2" and "clear step 3" statements, on the BackgroundService.pendingQueue.remove(); 该示例在BackgroundService.pendingQueue.remove();的“清除步骤2”和“清除步骤3”语句之间显示BackgroundService.pendingQueue.remove(); statement. 声明。 If you have a solution please reply with that solution 如果您有解决方案,请回复该解决方案

I can imagine your object is a kind of Queue. 我可以想象您的对象是一种队列。 If you try to remove an object on an empty queue the exception NoSuchElementException is thrown. 如果尝试删除空队列上的对象,则会引发NoSuchElementException异常。

So you need to check if the queue is not empty before trying to remove something: 因此,您需要在尝试删除某些内容之前检查队列是否不为空:

  if(!BackgroundService.pendingQueue.isEmpty()){
    BackgroundService.pendingQueue.remove();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM