2013-02-26 48 views
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; 
} 
+0

歡迎來到SO!不幸的是,這不是我們對SO的期望類型。閱讀[問]以瞭解我們如何期待答案。 – 2013-02-26 23:36:22

回答

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; 
} 
+0

Omg ...我發誓我試過這個。謝謝,它現在有效。上帝,我覺得愚蠢。 – 2013-02-26 23:16:30

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;