-1

Why autoboxing and unboxing of primitives not happens with Generics Java.

public static <T extends Number> T addNumber(T a , T b)
{
  int c = a*b;
  System.out.println(c);
  return c; 
}

Here why * operation can't be performed and why can't return c.Any help would be appreciable.

Pooja
  • 31
  • 5

2 Answers2

1
int c = a*b;

This statement actually works, since T is bounded by Integer, so after erasure, the types of a and b are Integer and they are unboxed to int.

return c;

This doesn't work since the return type of the method is not Integer, it is T, and even though <T extends Integer> and Integer is final, so T can only be Integer, the compiler doesn't allow that, since it doesn't take the finality of the type bound into account (i.e. as far as it's concerned, the method can accept instances of a sub-class of the type bound, and it can't auto-box int to any sub-class of the type bound).

Changing the return type to Integer will make the code pass compilation :

public static <T extends Integer> Integer addNumber(T a , T b){
  int c = a*b;
  System.out.println(c);
  return c;
}

Of course, it doesn't make sense to use Integer (or any final class) as a type bound for a generic type parameter.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • if it is not allowing a *b – Pooja Jul 20 '16 at 06:06
  • 2
    @Pooja But your type bound is `Integer` not `Number`. If you change the type bound to `Number`, `int c = a.intValue ()*b.intValue ();` will work instead. `Number` cannot be unboxed automatically to an int. – Eran Jul 20 '16 at 06:08
  • Thanks. I was considering Number to be autoboxed automatically. – Pooja Jul 20 '16 at 06:12
  • But if I extend it with Integer so why it can not return int even If Integer class can not be subclassed. – Pooja Jul 20 '16 at 06:13
  • @Pooja `int` can only be boxed to Integer. – Eran Jul 20 '16 at 06:18
1

Generics are not supposed to be used with primitive types. T indicates a type parameter which should be an object.
More reference
Why don't Java Generics support primitive types? Java Generics ? , E and T what is the difference?
Restrictions on generics

Community
  • 1
  • 1
Vishal Vijayan
  • 308
  • 1
  • 4
  • 13
  • Integer is also a wrapper class and if we do mathematics operation on its object it is allowed , So why not if T extends Integer – Pooja Jul 20 '16 at 06:05