How to compare generic classin java member generic type

It's hard for me to write a generic class in java whose common elements can be compared.

Below is a snippet of code that I wrote, but it gives me a compilation error.

public class TestClass <E extends Comparable<E>>{ private E data1; private E data2; public void fun(){ if(data1 > data2){ } } } 

This gives me an error saying that compare ('>') operations are not valid. In my understanding, if I extend Comparable, I should be able to do this operation.

+4
source share
1 answer

Java is not C ++ and does not have operator overloading. You need to use .compareTo() , which is provided by the Comparable interface. For instance:

 if(data1.compareTo(data2) > 0){ 
+6
source

Source: https://habr.com/ru/post/1388743/


All Articles