【问题标题】:Why is my list empty?为什么我的列表是空的?
【发布时间】:2014-01-15 17:52:08
【问题描述】:

我需要检查List a 中的所有元素是否肯定。我的方法使用(尝试使用)递归来检查元素是否 > 0。

我的错误消息抱怨列表为空。我显然在这里遗漏了一些简单的东西,所以请帮助我了解正在发生的事情。

static boolean allPositive(List a) {

    // If list is empty, show a warning message.
    if (a.isEmpty()){
        System.out.println("No elements in list!");
    }
      // If both head and tail are less than 0, return false.
       if (a.getHead() >= 0 && allPositive(a.getTail())) {
          return true;
      }
      // If there are elements < 0, return false.   
    return false;
    }

这是 List 类,我认为很标准:

public class List {

private boolean empty;
private int head;
private List tail;

// Constructor for List, creates a head and tail(another List).
public List(int head, List tail) {
    this.empty = false; 
    this.head = head;
    this.tail = tail;
}

public List() {
    this.empty = true;
}

// To add tail when creating List.
public static List cons(int head, List tail) {
    return new List(head,tail);
}

// Empty list.
public static List empty() {
    return new List();
}

public boolean getEmpty() {
    return this.empty;
}

public boolean isEmpty() {
    return empty;
}

错误提示:

线程“主”java.lang.IllegalStateException 中的异常:尝试 访问空列表的头部

但我使用的列表是在这里创建的:

List a = List.cons(1, List.cons(2, List.cons(3, List.cons(4, List.empty()))));

【问题讨论】:

    标签: list recursion head tail


    【解决方案1】:

    allPositive 递归并最终到达触发空消息的尾部。它还会在空元素上调用 getHead。

    如果您认为一个空列表都是肯定的,并且您不需要警告消息,请使用:

    static boolean allPositive(List a) {
        if (a.isEmpty()) {
            return true;
        } else {
            return (a.getHead() >= 0 && allPositive(a.getTail())
        }
    }
    

    如果您需要在空列表上显示警告消息,则需要执行以下操作:

    static boolean allPositive(List a) {
        if (a.isEmpty()) {
            System.out.println("No elements in list!");
        }
        // This internal method won't warn on the empty list encountered during recursion.
        return allPositiveInternal(a);
    }
    
    static boolean allPositiveInternal(List a) {
        if (a.isEmpty()) {
            return true;
        } else {
            return (a.getHead() >= 0 && allPositiveInternal(a.getTail())
        }
    }   
    

    【讨论】:

    • “内部”功能并不是真正需要的。如果列表为空,只需发出警告并返回 true。只有当你想在同一个程序中选择被警告或不被警告时,你才必须拆分(或添加一个参数“boolean verbose”左右)。
    • 如何区分每个非空列表的空尾和没有函数“内部”变体的空列表?
    • 谢谢,我可以看到空列表将在递归过程结束时被调用,因为它形成了最后一个尾部。空列表是正数对我来说似乎很奇怪,因为零既不是 +ve 也不是 -ve??我的逻辑适用于这个问题,但现在再次感谢。
    • @user2684301:您的函数对无法区分自身。如果“内部”函数会调用自身而不是 allPositive 函数,则会出现这种情况。那你就有道理了。
    • @Bennef:列表既不是正面的也不是负面的,除非它以某种方式定义。仍然对于空集的所有元素来说,一切都是真的。那是纯粹的逻辑。所以空列表的所有元素都为零,同时为正和负。如果你现在说,不存在这样的数字,我会回答,这正是空集中元素的数量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2017-09-10
    相关资源
    最近更新 更多