【问题标题】:Why am I getting the error "bad operand types for binary operator" in my methods?为什么我的方法中出现错误“二元运算符的操作数类型错误”?
【发布时间】:2016-11-16 23:52:06
【问题描述】:
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;
}

}

我在 largestsmallest 方法中的 if 语句中收到错误消息。我在排除错误方面没有运气。请帮忙。非常感谢。

【问题讨论】:

    标签: java generics arraylist operators operands


    【解决方案1】:

    a.get(int) 不能转换为原始数值类型(一般是Number,不能自动拆箱),所以不能使用&lt;&gt;

    您需要提供明确的Comparator&lt;T&gt;(或更一般地说,Comparator&lt;? super T&gt;),以允许您比较列表中的元素:

    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) {
          // ...
        }
        // ...
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      • 2016-06-24
      相关资源
      最近更新 更多