为什么我的清单是空的?

时间:2014-01-15 17:52:08

标签: list recursion head tail

我需要检查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;
}

错误说:

  

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

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

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

1 个答案:

答案 0 :(得分: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())
    }
}