How to write a generic Java method and compare two generic variables inside a method?

I wrote the following code:

private static <T> T getMax(T[] array) { if(array.length == 0) { return null; } T max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) max = array[i]; } return max; } 

The problem is this line: if(array[i] > max) .

I understand that Java cannot understand the > operator in the case of unknown / arbitrary classes.

At the same time, I do not want to write different methods for class objects, which, as I know, I will send.

Is there a workaround?

+5
source share
2 answers

You need to change T to T extends Comparable<T> and use the compareTo method. I.e:

  • private static <T extends Comparable<T>> T getMax(T[] array) and
  • if (array[i].compareTo(max) > 0) { ... }

But note that you can use

 maxElement = Collections.max(Arrays.asList(array)); 
+6
source

Yes, there is a workaround by adding a Comparable upper bound to T

Since the < operator does not work with objects, you should use the equivalent functionality, which is the compareTo method in the Comparable interface.

Verify that type T is Comparable by specifying an upper bound.

 private static <T extends Comparable<T>> T getMax(T[] array) 

Then, instead of the > operator > call compareTo :

 if(array[i].compareTo(max) > 0) 
+3
source

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


All Articles