P
P
parkito2016-08-07 22:31:21
Java
parkito, 2016-08-07 22:31:21

How to compare generics in java?

Hello. Please help me solve the following problem.
It needs to compile and work correctly:

public static void main(String[] args) {
            MyClass<Integer>a = new MyClass<Integer>(1);
            MyClass<Integer>b = new MyClass<Integer>(2);
            if (a>b)
            {
                System.out.println("true");
            }
        }

As I understand it, in order to be able to compare class objects, this class must implement the Comparable interface.
class MyClass<T extends Comparable<T>> implements Comparable<T> {
    T data;

    MyClass(T data) {
        this.data = data;
    }
    

    public int compareTo(T o) {
        return compare(this.data, o);
    }

    public int compare(T x, T y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
}

But now how to make the compare method correctly compare those who > (who can be compared with each other).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Gapchenko, 2016-08-07
@parkito

Java is not C++, not Kotlin, not Scala. There is no operator overloading, so do this:

if (a.compareTo(b) > 0) {
    doSomething();
}

In your case, it MyClassshould implement Comparable<MyClass<T>>, not Comparable<T>. In compare()it will be possible to compare with each other x.dataand y.data, which, in your case, are instances of a generic type that implements Comparable. Something like this:
class MyClass<T extends Comparable<T>> implements Comparable<MyClass<T>> {
    T data;

    MyClass(T data) {
        this.data = data;
    }

    @Override
    public int compareTo(MyClass<T> another) {
        return data.compareTo(another.data);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question