Search code examples
javaarraysgenericsoperator-keywordoperand

Java Error: Bad Operand Type for binary operator <


public class MaxMinArray<T>{

  private T getMin(T[] arr){

    T min = arr[0];
    for (int i = 0; i<arr.length; i++){
      min = (arr[i] < min) ? arr[i] : min;
    }
    return min;
  }

 public static void main(String[] args) {

  MaxMinArray<Integer> m = new MaxMinArray<Integer>();
  Integer[] arr = {1,2,3,4,5};
  System.out.println(m.getMin(arr));

  }

}

I am getting the following error. I dont understand why can I not use <, if T is a type variable and not an object ?

  error: bad operand types for binary operator '<'
      if (arr[i] < min){
                 ^
  first type:  T
  second type: T
  where T is a type-variable:
    T extends Object declared in class MaxMinArray

Also, since I am using T for generics, is it a good idea to define my array as Integer and not int. If not, how should I define an array of integers?

Thank you!


Solution

  • arr[i] contains some Object of some generic type T. You cannot use the < operator on an Object.

    Do this instead:

    public class MaxMinArray<T extends Comparable<T>> {
    
        private T getMin(T[] arr){
             T min = arr[0];
             for (int i = 0; i<arr.length; i++){
                 min = (arr[i].compareTo(min) < 0) ? arr[i] : min;
             }
             return min;
        }
        // ...