1
import java .util.*;
import java.io.*;
class MaxIt<T extends Number >
    {
   T x;
 public T maxi(T a,T b)
  {
    if(a>b)
        return a;
    else
        return b;
  }
}
public class MaxGen{
     public  static void main(String[] args)
 {

    MaxIt<Integer> i=new MaxIt<Integer>();
    System.out.println("enter two integer ");
    int a,b;
    Scanner sc=new Scanner(System.in);
    a=sc.nextInt();
    b=sc.nextInt();
    System.out.println(a,b);

} }

I was reading about generic, so i have tried to make a generic program for finding maximum of two numbers but when i am compiling this it is giving me an error saying that - bad operand type for binary operator '>'. can u tell me what is wrong in this code?

Shubham Tyagi
  • 181
  • 1
  • 3
  • 14
  • You have used local variables and not initialized them..this shouldn't compile. – minigeek Mar 12 '17 at 06:08
  • Possible duplicate of [Java comparing generic types](http://stackoverflow.com/questions/20793082/java-comparing-generic-types) – Guy Mar 12 '17 at 06:09
  • 1
    You can't use `<` on a `Number` directly. You can use it on a `Number`'s `doubleValue()` though. – D M Mar 12 '17 at 06:23

1 Answers1

1

You should be using Comparable, and you might make the method static and it could take a variable number of arguments. Something like,

public static <T extends Comparable<? super T>> T maxi(T... vals) {
    if (vals == null || vals.length == 0) {
        return null;
    }
    T m = vals[0];
    for (int i = 1; i < vals.length; i++) {
        if (m.compareTo(vals[i]) < 1) {
            m = vals[i];
        }
    }
    return m;
}

Then you need to actually call it. Something like,

System.out.println(maxi(a,b));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • ok now it is working.But i could not understand two things.1. super T> and 2.why we cannot use '<' . – Shubham Tyagi Mar 12 '17 at 06:16
  • 1
    **1.** [What is PECS (Producer Extends Consumer Super)?](http://stackoverflow.com/q/2723397/2970947) **2.** Because Java does **not** have [*operator overloading*](https://en.wikipedia.org/wiki/Operator_overloading). – Elliott Frisch Mar 12 '17 at 06:47