Casting an object in equals Java 5

T

Tom Anderson

Cute, but off the point. In fact as a developer of an API, Tom very
well can be confident of something because he actually did make it so,
and that was his point. You had it exactly backwards - confidence
didn't make it safe, making it safe made him confident.

Also, i have godlike superpowers.

tom
 
D

Daniel Pitts

crazzybugger said:
Hi,
I am stuck with a compiler warning while trying to cast an
object inside equals method.
Consider class A<I>{ }
inside this class, I am trying to override equals method. However, I
am not able to cast the received object into the proper type without
compiler warning.

Consider this implementation of equals
public boolean equals(Object that){
if(that instanceof A){
A<I> that1 = this.getClass().cast(that); // here I am
getting compiler warning.
// perform comparisons...
}
}

what is the right way to cast here ?
thank you...

Unfortunately, this is a problem with erasure, there is no 100%
"correct" way to do this.

You can use @SuppressWarnings({"unchecked"}).
 
D

Daniel Pitts

Andreas said:
Another caveat with this approach:
if some subclass's equals() calls super.equals(), it may
get (unexpected) wrong negatives, even for identical
objects...
The proper idiom is:
if (obj.getClass() != this.getClass() {
return false;
}
 
A

Andreas Leitgeb

Daniel Pitts said:
The proper idiom is:
if (obj.getClass() != this.getClass() {
return false;
}

And even this is not "proper", but an indication of a design
error that led one to this strange need, in the first place.

Skim the whole thread until you find the relevant subthreads...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top