GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How this program produce Classcast Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How this program produce Classcast Exception" Watch "How this program produce Classcast Exception" New topic
Author

How this program produce Classcast Exception

Kir Swa
Greenhorn

Joined: May 03, 2012
Posts: 9
Source of the code: Exam Lab
the answer of this Question is equals() can produce Classcast Exception, but i am not getting any exception when i execute. In which case this program raise the Classcast Exception



Can some one help me?
Thanks in advance

[Added code tags - see UseCodeTags for details]
W Lin
Greenhorn

Joined: Mar 16, 2012
Posts: 11
public boolean equals(Object o)
{
if( !(o instanceof Stc) )
return false;

return this.hashCode()==((Stc)o).hashCode();
}

Kir Swa wrote:Source of the code: Exam Lab
the answer of this Question is equals() can produce Classcast Exception, but i am not getting any exception when i execute. In which case this program raise the Classcast Exception
public boolean equals(Object o)
{
return this.hashCode()==((Stc)o).hashCode();
}




Can some one help me?
Thanks in advance

[Added code tags - see UseCodeTags for details]
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1509
    
    5

Hello Kir Swa,

Welcome to CodeRanch!

Kir Swa wrote:the answer of this Question is equals() can produce Classcast Exception

Well, what is the question? I didn't see any question regarding it.

But yes, the equals method can throw ClassCastException. The reason is - on line 11 (by the way, its good to see code tags in your first post itself!), you are casting object of class 'Object' into Stc. What if you pass an Integer, or String to equals method? I guess you got the idea.

It is good practice to write equals method like this:

I hope this helps.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Kir Swa
Greenhorn

Joined: May 03, 2012
Posts: 9
Anayonkar Shivalkar wrote:Hello Kir Swa,

Welcome to CodeRanch!

Kir Swa wrote:the answer of this Question is equals() can produce Classcast Exception

Well, what is the question? I didn't see any question regarding it.

But yes, the equals method can throw ClassCastException. The reason is - on line 11 (by the way, its good to see code tags in your first post itself!), you are casting object of class 'Object' into Stc. What if you pass an Integer, or String to equals method? I guess you got the idea.

It is good practice to write equals method like this:

I hope this helps.



Hi Anayonkar Shivalkar,

I got it now. thank you so much.
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1509
    
    5

You are welcome.
 
GeeCON Prague 2014
 
subject: How this program produce Classcast Exception