2013-11-20 96 views
0

我有一種方法來合併兩個相同類型的列表。返回Collections.emptyList()失敗,三元運算符

public <T> List<T> mergeList(List<T> first, List<T> second) { 


    if(first != null && second != null && (first.addAll(second))){ 

     return first; 
    } else { 

     return Collections.emptyList(); 
    } 
} 

有沒有問題,如果使用的if-else塊,但與三元運算符:

public <T> List<T> mergeList(List<T> first, List<T> second) { 

    return (first != null && second != null && first.addAll(second)) ? first : Collections.emptyList(); 

} 

Eclipse中說:Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<T>

爲什麼我不能回到這裏Collections.emptyList()?我認爲三元運算符會被編譯器當作if-else處理?

+1

你試過了嗎?收藏。 emptyList();' – OldCurmudgeon

+0

那麼重複已經回答了它... –

回答

2

您需要:

public <T> List<T> mergeList(List<T> first, List<T> second) { 

    return (first != null && second != null && first.addAll(second)) 
    ? first 
    : Collections.<T>emptyList(); 

} 

注意使用Collections.<T>emptyList()代替Collections.emptyList()