2016-11-16 119 views
-1
public class t<T extends Number>{ 

private ArrayList<T> a = new ArrayList<T>(); 

public void add(T x){ 

    a.add(x); 
} 

public T largest(){ 

    T large = a.get(0); 
    int count = 1; 

    while(a.get(count)!=null){ 

    if(a.get(count)>large) 
     large = a.get(count); 
    count++; 
    } 
    return large; 
} 

public T smallest(){ 

    T small = a.get(0); 
    int count = 1; 

    while(a.get(count)!=null){ 

    if(a.get(count)<small) 
     small = a.get(count); 
    count++; 
    } 
    return small; 
} 

}爲什麼我在我的方法中出現錯誤「二元運算符的錯誤操作數類型」?

我收到錯誤在我如果陳述我的最大最小方法中。我在排除錯誤方面沒有運氣。請幫忙。非常感謝你。

回答

2

a.get(int)是無法轉換爲原始的數字類型(這是Number,一般情況下不能進行自動拆箱),所以你不能使用<>

您需要提供一個明確的Comparator<T>(或者更一般地說,Comparator<? super T>),讓你比較列表的元素:

public class t<T extends Number>{ 
    private Comparator<? super T> comparator; 

    t(Comparator<? super T> comparator) { 
    this.comparator = comparator; 
    } 

    public T largest(){ 
    // ... 
    if (comparator.compare(a.get(count), large) > 0) { 
     // ... 
    } 
    // ... 
    } 
} 
相關問題