This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic Program Warning

 
James Chegwidden
Author
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, trying to learn write generic programs- not quite like C++ templates...I have the following generic program.



I compiled it an got the following warning


Would you fix this warning using exception handling. JC
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can rid yourself of the warning by returning a Number and not a T.
The warning is coming from this line:

return (T) sum;

You declare T as a subclass of Number, and *sum* is a variable of type Number. A superclass is not always able to be cast to a subclass. (i.e. String is a subclass of Object, but you can't just cast any Object to a String). This code compiles without warning:

because any subclass can be referred to by a superclass reference.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler is complaining because you are casting a Number to a T. This makes sense since you declared the function to return a T which needs to extend Number, but how do you know that sum is really the same run-time type as T and not some other class that extends Number? Well perhaps you do, but the compiler cannot tell since sum was declared as a Number.

I'm not too familiar with templates, but I think you can declare sum as a T instead. The other option, as Garrett pointed out, is to declare the function to return a Number instead of a T.

Layne
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Layne Lund: I'm not too familiar with templates, but I think you can declare sum as a T instead.

This poses problems because :

sum = sum.doubleValue() + elem.doubleValue();

returns a double which cannot be autoboxed into a T. (I only know bc that was the first solution I tested).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic