Filip5991
Filip5991

Reputation: 443

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?

Upvotes: 1

Views: 1567

Answers (3)

pinakin
pinakin

Reputation: 442

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());

    }
}

Upvotes: 3

ZINE Mahmoud
ZINE Mahmoud

Reputation: 1332

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       Triple<Integer> test = new Triple<>(1, 4, 5);
       System.out.println(test.max());

       }

}


class Triple<T extends Number<T> & Comparable<T>> {
    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();
        }
    }
  }

}

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35096

Just return T instead of double

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

Upvotes: 0

Related Questions