如果数组列表为空,则此代码将返回错误。我需要添加代码以避免错误,如果它为空则返回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;
}
答案 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;
}
试试这个。它对空数组没有问题,但它会返回一个假Comment
,voteCount
设置为0
;