0

如果数组列表为空,此代码将返回错误。我需要添加代码以避免错误,如果为空则返回 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;
}
4

2 回答 2

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;
}
于 2013-02-26T23:14:24.947 回答
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;
}

尝试这个。空数组不会有问题,但它会返回一个Comment设置voteCount0;

于 2013-02-26T23:17:43.993 回答