aspose file tools*
The moose likes Beginning Java and the fly likes Generic Program Warning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generic Program Warning" Watch "Generic Program Warning" New topic
Author

Generic Program Warning

James Chegwidden
Author
Ranch Hand

Joined: Oct 06, 2002
Posts: 201
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


Author and Instructor, my book
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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.


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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


Java API Documentation
The Java Tutorial
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic Program Warning