0

I'm wrote a simple method with generic to add Integers, floats and double but got getting an syntx error when adding two objects. Not sure how to achieve this with generics.

package pack;

public class Main7 {

public static <E> void addData(E objA, E objB)
{
    System.out.println(objA+objB); //getting error that + operator not allowed
}

public static void main(String[] args) {

Integer objA = new Integer(10);
Integer objB = new Integer(20); 

Float objF = new Float(10.01);
Float objG = new Float(11.01);

addData(objA, objB);
addData(objF, objG);

}

}
user1925406
  • 713
  • 3
  • 15
  • 33
  • It's not possible, sorry. – Radiodef May 12 '15 at 19:02
  • Your method signature is unrestricted in what `E` can be. There's nothing to prevent calling code like `addData(new Date(), new Date())`. The compiler is right to complain that it doesn't know how to handle that. Try method overloading instead. – Ted Hopp May 12 '15 at 19:04
  • The `+` operator is only defined for _primitive_ numeric types. – GriffeyDog May 12 '15 at 19:06

0 Answers0