需要添加代码以将空数组返回为null

时间:2013-02-26 23:11:09

标签: arrays testing

如果数组列表为空,则此代码将返回错误。我需要添加代码以避免错误,如果它为空则返回null。感谢

public Comment findMostHelpfulComment()
{
    Iterator<Comment> it = comments.iterator();
    Comment best = it.next();
    while(it.hasNext()) 
    {
        Comment current = it.next();
        if(current.getVoteCount() > best.getVoteCount()) {
            best = current;
        }
    }

return best;
}

2 个答案:

答案 0 :(得分:3)

public Comment findMostHelpfulComment()
{
    if (comments.isEmpty()) {
        return null;
    }

    // rest of method
}

或者,如果您稍微重做循环,则可以从null最佳评论开始。

public Comment findMostHelpfulComment()
{
    Comment best = null;

    for (Comment current: comments) {
        if (best == null || current.getVoteCount() > best.getVoteCount()) {
            best = current;
        }
    }

    return best;
}

答案 1 :(得分:0)

public Comment findMostHelpfulComment()
{
    Iterator<Comment> it = comments.iterator();
    Comment best = new Comment();
    best.setVoteCount(0);
    while(it.hasNext()) 
    {
        Comment current = it.next();
        if(current.getVoteCount() > best.getVoteCount()) {
            best = current;
        }
    }
    return best;
}

试试这个。它对空数组没有问题,但它会返回一个假CommentvoteCount设置为0;