2016-11-16 122 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) { 
     // ... 
    } 
    // ... 
    } 
} 
相关问题