The task: to write a method that should take as input two numbers of any integer or real type and return their sum. Be sure to use generics .

 public class Generics { public static void main(String[] args) { Generics myClass = new Generics(); System.out.println(myClass.add(3, 2.0)); } public static <T extends Number> double add(T firstNumber, T secondNumber) { Double n1 = (Double) firstNumber; Double n2 = (Double) secondNumber; double res = n1 + n2; return (res); } } 

At performance I receive: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double . What should be done in this case?

  • 3
    double a = firstNumber.doubleValue(); double b = ... double a = firstNumber.doubleValue(); double b = ... - Sergey

0