-4

I wanted to check, if my Generics are of the type Integer. If they are, they should get converted to double and afterwards should be added together. I get the error "The operator * is undefined for the argument type(s) E, double". There is also the same problem afterwards with adding the two casted values together.

How can I fix this?

Thanks in advance :)

public void add(E value1, E value2) {
            if(value1 instanceof Integer && value2 instanceof Integer) {
                double valueCast1 = value1 * 1.0; 
                double valueCast2 = value2 * 1.0;
                System.out.println(value1 + value2);
            }
        }
  • 1
    Why would you write code like this? – Kayaman Oct 18 '17 at 14:33
  • I think what Kayaman maybe asking is why would you want to multiply something by 1. – Griffin Oct 18 '17 at 14:35
  • Java and JavaScript are two different languages... *1.0 is for javascript... – Alexei Levenkov Oct 18 '17 at 14:36
  • 1
    Well the body itself is nonsense of course. The code is also in no way generic. Sure, there's the generic type `E`, but it might as well just be `Object`. – Kayaman Oct 18 '17 at 14:37
  • https://stackoverflow.com/a/13253018/8796090 – Simon Heinz Oct 18 '17 at 14:38
  • 2
    The main question would be why you would use two generic parameters for a method that only does something if you supply two integers which are then attempted to cast (incorrectly) to doubles and have their sum printed. – Rob Obdeijn Oct 18 '17 at 14:39
  • I think you misunderstand how generics are intended to work. This doesn't work because there's no guarantee that your generic type `E` can be successfully cast to Integer, Double or anything else. You have to explicitly, not implicitly cast, even after you've checked the `instanceof`. – PaulProgrammer Oct 18 '17 at 19:41

1 Answers1

1

You must add a cast for your Integer values. You've previously checked if they were Integer, but in sentences

double valueCast1 = value1 * 1.0; 
double valueCast2 = value2 * 1.0;

they still be just generic E classes. You must specify that they should be considered integer so

double valueCast1 = (Integer)value1 * 1.0; 
double valueCast2 = (Integer)value2 * 1.0;

That's it.

alseether
  • 1,889
  • 2
  • 24
  • 39