Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2005

Tip: Looking for answers? Try searching our database.

confusion about instanceof and generics

Thread view: 
d4@thispla.net - 08 Dec 2005 10:50 GMT
Dear all,

sorry, I'm still confused about instanceof and generics although I read
several good introductions and explanations.

My question is:  If A is an abstract class, how can I write a test that
succeeds for all instances
of subclasses of A (and fails for all others ;-)?

I short, I have the following situation:
I have an abstract class A with several subclasses B, C, ...

There is an easy way of comparing subclasses of A for equality.  In
particular, this comparison gurarantees that no two instances of
subclasses of A are found to be equal unless they are an instance of
the same subclass.

In other words "boolean equal(Object other)" can be the same for all
subclasses of A and therefore I want to override it in A.

My approach is

@Override
boolean equals(Object other)
{
    if(!(other instanceof A))
    {
         // error
    }

    return compare(this, (A) other);
}

But that does not work because !(other instanceof A) is true for all
instances of subclasses of A.

How can I write a test that succeeds for all subclasses of A?

Thank you,

Uli
Ingo R. Homann - 08 Dec 2005 11:16 GMT
Hi,

> My approach is
>
[quoted text clipped - 11 lines]
> But that does not work because !(other instanceof A) is true for all
> instances of subclasses of A.

I do not see what this has to do with generics, but how about:

if(getClass()!=other.getClass())

or

if(!getClass().equals(other.getClass()))

or ...

Ciao,
Ingo
d4@thispla.net - 08 Dec 2005 11:41 GMT
I have to apologize - there was an error somewhere else. (Nevertheless,
generics still confuse me).

But thank you anyway - I didn't realize that I could complare classes
the way you suggested.

Uli
Thomas Hawtin - 08 Dec 2005 18:05 GMT
>> @Override
>> boolean equals(Object other)
>> {
>>      if(!(other instanceof A))
>>      {
>>           // error

It's not an error.

>>      }
>>
[quoted text clipped - 5 lines]
>
> I do not see what this has to do with generics, but how about:

Other than it doesn't work on generic types. It compares the objects
erasure, so you cannot distinguish, say, ArrayList<String> from
ArrayList<JComponent>.

> if(getClass()!=other.getClass())

In the case of equals, that should read:

        if (other == null || this.getClass() != other.getClass()) {
            return false;
        }

(Or split into separate if statements, if you value readability.)

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Oliver Wong - 08 Dec 2005 19:00 GMT
>> if(getClass()!=other.getClass())
>
[quoted text clipped - 3 lines]
>             return false;
>         }

   It's not a hard requirement that classes of two different objects be
non-equal. For example I usually code my equals() method so that
occasionally an object of type ImmutableFoo can be found to be equal to an
object of type MutableFoo.

   You just gotta make sure the contract for the equals() method is
satisfied (reflexive, symmetric, transitive, consistent, non-null). See
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)

   If you're overriding equals(), you'll probably have to also override
hashCode(), and generally be careful around Comparator and/or Comparable.

   - Oliver
Thomas Hawtin - 08 Dec 2005 20:28 GMT
>     It's not a hard requirement that classes of two different objects be
> non-equal. For example I usually code my equals() method so that
> occasionally an object of type ImmutableFoo can be found to be equal to an
> object of type MutableFoo.

You are shooting off at a tangent. The context of the thread is
distinguishing between a class and its subclasses.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Roedy Green - 08 Dec 2005 11:41 GMT
>There is an easy way of comparing subclasses of A for equality.  In
>particular, this comparison gurarantees that no two instances of
>subclasses of A are found to be equal unless they are an instance of
>the same subclass.

use of getClass and instanceof is a usually a sign you are not writing
OO code, but are trying to solve your problems procedurally.

What is the problem you are trying to solve?  Likely people will show
you how to do it without getClass or instanceof.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

d4@thispla.net - 08 Dec 2005 12:04 GMT
Thank you Roedy,

I realized that you've answered now several of my questions in a
helpful way.  Thank about that.

> What is the problem you are trying to solve?

I suppose my initial posting describes quite accurately what I'm trying
to do. In which respect could I be more precise?

> Likely people will show you how to do it without getClass or instanceof.

In "Object.equals(Object other)" the other object always has the type
Object.  From my current knowledge I guess that if you override equals
you almost always have to use a cast here unless equality is computed
via reference equality.

And if you cast "object" to an apropriate type, you first want to know
whether this is allowed: alas, use of instance of.  How could I do it
without?

Uli
Oliver Wong - 08 Dec 2005 18:42 GMT
>> What is the problem you are trying to solve?
>
> I suppose my initial posting describes quite accurately what I'm trying
> to do. In which respect could I be more precise?

   I think what Roedy means here is that you initially wanted to do some
task A, and the only way you can think of to do it is by using technique B,
so you post on the newsground "How do I do B?" but really, the problem you
are trying to solve is A.

   It's sort of like Person 1 posting "What kind of chainsaw should I buy
to widen the front door to my house?"

   Person 2 replies "Why are you trying to widen the front door to your
house?"

   Person 1 says "I want to get into my house, but I can't fit my car
through the front door."

   Person 2 says: "Why don't you try getting out of the car first?"

   Person 1 says: "Damn! I didn't realize I could do that! Thanks!"

   - Oliver
Roedy Green - 08 Dec 2005 23:48 GMT
>I suppose my initial posting describes quite accurately what I'm trying
>to do. In which respect could I be more precise?

That is not what I meant by your problem. In what practical situation
do you find yourself wanting to write code like that?

In what context did this come up?
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.