如何返回队列是空的错误?

时间:2015-02-17 22:36:40

标签: java

如果队列为空,如何抛出错误?

public T dequeue() {
        T o = null;
        if (head != null) {
            o = head.getData();
            head = head.getNext();
            queueSize--;
        }
        return o;

2 个答案:

答案 0 :(得分:0)

如果queue为空,则没有头节点。因此,在检查中创建一个else子句,使头部为空。

 public T dequeue() {
    T o = null;
    if (head != null) {
        o = head.getData();
        head = head.getNext();
        queueSize--;
    }
    // Otherwise, the head is null
    else{
       // Throw exception
       throw new NoSuchElementException()
    }
    return o;

答案 1 :(得分:0)

throw new NoSuchElementException() if head == null