newday
newday

Reputation: 3878

How to find the maximum number using Generics?

I need to implement a method that compute the maximum number when three numbers are provided using Generics. I know how to do this using Comparable class but I need to use only numbers.

This is the code.

 public static <T extends Math>  T compareThreeValue(T x, T y, T z){ 
     T max=Math.max(Math.max(x, y), z);
     return max; 
 }

I added this code to get idea of what I am trying.

Upvotes: 1

Views: 2177

Answers (1)

Thinesh Ganeshalingam
Thinesh Ganeshalingam

Reputation: 723

As All Primitive Wrappers for digits extends Number and they implement Comparable you could do

 public static <T extends Number & Comparable<T>> T max(T x, T y, T z) {
    return max(max(x, y), z);
}

public static <T extends Number & Comparable<T>> T max(T x, T y) {
    if (x.compareTo(y) > 0) {
        return x;
    }
    return y;
}

Also you could use

Collections.max(Arrays.asList(x,y,z))

as all numbers are Comparable. But you will have performance overhead of for creation of a new list.

Upvotes: 5

Related Questions