Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException

 
Saibabaa Pragada
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Why I am getting this exception.
 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It compiles for me.

 
Saibabaa Pragada
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, This question is about Runtime ClassCastException. It throws ClassCastException because TreeSet cannot sort its elements (Double and Integer) at Runtime. My question is, How do we know that 0xCAFE is an Integer.
Henry Wong wrote:
It compiles for me.

 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saibabaa Pragada wrote:Hi, This question is about Runtime ClassCastException. It throws ClassCastException because TreeSet cannot sort its elements (Double and Integer) at Runtime. My question is, How do we know that 0xCAFE is an Integer.


Oops.... apologies. Wasn't paying attention.

Literals that start with 0x are hexidecimal numbers. They are integer literals, unless they end with L, then they are long literals.

Henry
 
Imad Aydarooos
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Saibabaa, actually the problem is caused by the line (add(3.7)) which is a double autoboxed into Double , when it compared to the Integer value provided by the second line the stack trace is:
at java.lang.Integer.compareTo(Integer.java:35)
which states clearly that we cannot compare a Double to Integer
NOTE: any integral literal is of type int, any floating point literal is of type double

Regrads
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Saibabaa Pragada wrote:Hi, This question is about Runtime ClassCastException. It throws ClassCastException because TreeSet cannot sort its elements (Double and Integer) at Runtime. My question is, How do we know that 0xCAFE is an Integer.


Oops.... apologies. Wasn't paying attention.

Literals that start with 0x are hexidecimal numbers. They are integer literals, unless they end with L, then they are long literals.

Henry


Henry is correct. Because, you've stored a double value into the collections, which takes abstract Number as the parameter, we unable to compare the first Double and the Integer. Have a look on the below code snaps!

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic