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

Arrays 需要添加代码以将空数组返回为null,arrays,testing,Arrays,Testing,如果数组列表为空,此代码将返回错误。我需要添加代码以避免错误,如果为空则返回null。谢谢 public Comment findMostHelpfulComment() { Iterator<Comment> it = comments.iterator(); Comment best = it.next(); while(it.hasNext()) { Comment current = it.next(); if

如果数组列表为空,此代码将返回错误。我需要添加代码以避免错误,如果为空则返回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;
}
public Comment findMostHelpfulComment()
{
Iterator it=comments.Iterator();
Comment best=it.next();
while(it.hasNext())
{
Comment current=it.next();
if(current.getVoteCount()>best.getVoteCount()){
最佳=电流;
}
}
回报最好;
}
或者,如果稍微修改循环,可以从
null
最佳注释开始

public Comment findMostHelpfulComment()
{
    Comment best = null;

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

    return best;
}
或者,如果稍微修改循环,可以从
null
最佳注释开始

public Comment findMostHelpfulComment()
{
    Comment best = null;

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

    return best;
}
public Comment findMostHelpfulComment()
{
Iterator it=comments.Iterator();
注释最佳=新注释();
最佳设定值(0);
while(it.hasNext())
{
Comment current=it.next();
if(current.getVoteCount()>best.getVoteCount()){
最佳=电流;
}
}
回报最好;
}
试试这个。空数组不会有问题,但它将返回一个虚拟的
注释
,并将
voteCount
设置为
0

public Comment findMostHelpfulComment()
{
Iterator it=comments.Iterator();
注释最佳=新注释();
最佳设定值(0);
while(it.hasNext())
{
Comment current=it.next();
if(current.getVoteCount()>best.getVoteCount()){
最佳=电流;
}
}
回报最好;
}

试试这个。空数组不会有问题,但它将返回一个虚拟的
注释
,并将
voteCount
设置为
0

天哪。。。我发誓我试过了。谢谢,现在可以用了。天哪,我觉得自己很笨。天哪。。。我发誓我试过了。谢谢,现在可以用了。天哪,我觉得自己很笨。欢迎来到SO!不幸的是,这不是我们所期望的问题类型。通过阅读了解我们对答案的期望。欢迎来到SO!不幸的是,这不是我们所期望的问题类型。通过阅读了解我们对答案的期望。
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;
}