Vlad Paskevits
Vlad Paskevits

Reputation: 388

Generic compareTo class

I want to make somehow generic type class, with method named leiaSuurem. Objective is to compare two integer, which one is bigger. If, for example, x is bigger than y, then x is max.

public class Vordleja  {
    public int leiaSuurem <T extends Comparable<T>> T
    maksimum(T x, T y){
        T max = x;
        if(y.compareTo(max) > 0) max = y;
        if(x.compareTo(y) > 0) max = x;
        return max;
    }

    public void main(String[] args) {
        System.out.println("Largest ( 3, 4 ) element is : " + maksimum(3, 4));
    }
}

Upvotes: 1

Views: 52

Answers (1)

Michael
Michael

Reputation: 44130

That's not a valid method signature. You have what looks like two method names (leiaSuurem and maksimum), and two return types (int and T). The correct signature should be public <T extends Comparable<T>> T maksimum(T x, T y).

Also your main method must be static, and therefore maksimum must also be changed to static to be called from within main:

public class Vordleja  {
    public static <T extends Comparable<T>> T maksimum(T x, T y){
        T max = x;
        if(y.compareTo(max) > 0) max = y;
        if(x.compareTo(y) > 0) max = x;
        return max;
    }

    public static void main(String[] args) {
        System.out.println("Largest ( 3, 4 ) element is : " + maksimum(3, 4));
    }
}

Upvotes: 3

Related Questions