Search code examples
javagenericscastingdoublegeneric-programming

double method inside a generic class in java


I am trying to create a generic class that would work with 3 numbers in java (int, float and double in my case).

Inside this class i want a double method that would return the maximum number of the 3, but i have trouble returning a double since it's a generic class.

class Triple<T extends Comparable> {
    T a;
    T b;
    T c;

    public Triple(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    double max() {
        if (a.compareTo(b) > 0 && a.compareTo(c) > 0) {
            return (double) a;
        } else {
            if (b.compareTo(c) > 0) {
                return (double) b;
            } else {
                return (double) c;
            }
        }
    }

}

This is what i have so far, but when testing it with integers, i get the following error:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

Any help on how to return a primitive type from a generic class?


Solution

  • You can have generic extends Comparable and Number. This way we can call doubleValue() present in Number class instead of casting it into double.

    class Triple<T extends Number & Comparable> {
        T a;
        T b;
        T c;
    
        public Triple(T a, T b, T c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    
        double max() {
            if (a.compareTo(b) > 0 && a.compareTo(c) > 0) {
                return a.doubleValue();
            } else {
                if (b.compareTo(c) > 0) {
                    return b.doubleValue();
                } else {
                    return c.doubleValue();
                }
            }
        }
    
    }
    
    
    public class Main {
    
        public static void main(String[] args)  {
            Triple<Integer> triple = new Triple<>(1, 2, 3);
    
            System.out.println(triple.max());
    
        }
    }