Answer the question
In order to leave comments, you need to log in
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");
}
}
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);
}
}
Answer the question
In order to leave comments, you need to log in
Java is not C++, not Kotlin, not Scala. There is no operator overloading, so do this:
if (a.compareTo(b) > 0) {
doSomething();
}
MyClass
should implement Comparable<MyClass<T>>
, not Comparable<T>
. In compare()
it will be possible to compare with each other x.data
and 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 questionAsk a Question
731 491 924 answers to any question