• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java generic error  RSS feed

 
asit dhal
Greenhorn
Posts: 13
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just look at the following code..



Why the following error comes

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method doubleValue() is undefined for the type T

at Sum.total(BoundedGen.java:30)
at BoundedGen.main(BoundedGen.java:13)


please help me .
 
Nitin Surana
Ranch Hand
Posts: 129
Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use <T extends Double>
 
asit dhal
Greenhorn
Posts: 13
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it passible without doing anything like this ?

Here the class can be any native type or string type(Intereger/floating point data type will be added and strings will be concatenated).
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what your last question was referring to. However in your original post, if T can be any class, then you can't call the doubleValue() method on it because not every class has such a method. So if you want that code to compile, then T must be restricted so that it can only represent a class which does have a doubleValue() method. Nitin's reply does just that.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<T extends Double> is superfluous. Double is final, which would mean there is only one value for T - Double itself.
However, there is a better bound: <T extends Number>. java.lang.Number is the abstract base class of all primitive number wrapper classes, as well as BigDecimal and BigInteger, and it has the doubleValue() method.

As for taking String, the only common super types between String and Integer / Double / Float / ... are java.lang.Object and java.io.Serializable. Neither defines any method you can call to get a double value.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!