Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

java - Generics with autoboxing and unboxing of primitives

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...