• Post Reply Bookmark Topic Watch Topic
  • New Topic

cast error?  RSS feed

 
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys I'm getting a cast exception the exception is saying it an object of type Body can't be casted to Body.Key but the thing is I'm not casting from a Body to a Body.Key in the Body's equals method I m clearly passing an object of type object into the key.equals method yet it's telling me that I'm trying to convert a body to a Body.Key I must be missing something simple?

this is the line of code in question



Exception in thread "main" java.lang.ClassCastException: Body cannot be cast to Body$Key
at Body$Key.equals(Body.java:102)
at Body.equals(Body.java:60)


Thanks




 
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you post the main() method used for testing the code?
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I removed the above block of code and it worked fine but I would love to know how come I can't add two of the same entries into a HashSet,when I do the same for my HashMap I get no exception and the code just discards the second(duplicate) entry,keeps one of them and continues to run with no exceptions?

thanks
 
Norm Radder
Rancher
Posts: 2240
28
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks like the HashSet planets is expecting the equals method to work on Body objects, not Key objects so it is trying to compare two Body objects.  No Key objects are involved/

If you want Body objects to be considered equal when they have the same Key objects, compare the two Body objects' Key members.
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
very good point,thanks Norm
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!