0

I need a non-generic class containing a method with two generic parameters . In this method my goal is to compare two generic parameters and return the greater value. How can I do it?

public class generic <T extends Comparable<T>>{

    public T Max( T pv, T sv){
        if(pv.compareTo(sv)>=0){
            return pv;
        }else {
            return sv;
        }
    }

    public static void main(String[]args){
        generic g = new generic();
        System.out.println(g.Max( 2, 7));
    }
}
Megan
  • 43
  • 5
  • Why not `Collections.max(Arrays.asList(foo, bar));`? Or, some other means... Basically, you can do this with a generic method, there is no need for a generic *class*. – Andy Turner Jul 09 '20 at 10:26
  • @AndyTurner "there is no need for a generic *class*" I'm fairly sure they understand that, and didn't want one, but didn't know the syntax to construct it. – Michael Jul 09 '20 at 10:34
  • @Michael ok: but the term "generic method" is a good nudge towards [finding the syntax](https://docs.oracle.com/javase/tutorial/extra/generics/methods.html). – Andy Turner Jul 09 '20 at 10:38

1 Answers1

1

Just move it to the method declaration

public class Generic {

    public <T extends Comparable<T>> T max( T pv, T sv){
        if (pv.compareTo(sv) >= 0) {
            return pv;
        } else {
            return sv;
        }
    }

    public static void main(String[]args){
        Generic g = new Generic();
        System.out.println(g.max(2, 7));
    }
}

Also the method could be static, because it does not rely on any state. It would make calling it easier

System.out.println(max(2, 7));
Gyro Gearless
  • 5,131
  • 3
  • 18
  • 14
Michael
  • 41,989
  • 11
  • 82
  • 128