Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write generic Java method and compare two variables of the generic type inside the method?

I have written 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 in this line: if(array[i] > max).

I understand that Java can't understand the > operator in case of unknown/arbitrary classes.

At the same time, I don't want to write different methods for the objects of the classes that I know I'll be sending.

Is there a workaround?

like image 408
soham Avatar asked Mar 27 '15 21:03

soham


People also ask

How do you write a generic method in Java?

Example: Create a Generics Method Here, the type parameter <T> is inserted after the modifier public and before the return type void . We can call the generics method by placing the actual type <String> and <Integer> inside the bracket before the method name. demo. <String>genericMethod("Java Programming"); demo.

How does a generic method differ from a generic type in Java?

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.

Can you give an example of a generic method?

For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well. There are some fundamental differences between the two approaches to generic types.


2 Answers

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

  • 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));
like image 130
aioobe Avatar answered Nov 14 '22 23:11

aioobe


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

Because the < operator doesn't work on objects, you must use the equivalent functionality, which is the compareTo method in the Comparable interface.

Ensure that the type T is Comparable by providing an upper bound.

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

Then, in place of the > operator, call compareTo:

if(array[i].compareTo(max) > 0)
like image 22
rgettman Avatar answered Nov 14 '22 22:11

rgettman