The moose likes Java in General and the fly likes List instanceof class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "List instanceof class" Watch "List instanceof class" New topic

List instanceof class

Aggarwal Arpit
Ranch Hand

Joined: Mar 04, 2012
Posts: 86
Please help me in understanding the line (list.get(i) instanceof IdNamePair) in code below.
Here IdNamePair and IdvaluePair both are POJO classes with setters and getters.

Thanks in Advance
R. Jain
Ranch Hand

Joined: Aug 11, 2012
Posts: 375

It is just checking the type of the object stored in the List, whether it is of type IdNamePair or IdValuePair...
According to that it does the typecasting, to call the appropriate method in those classes..
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

instanceof checks to see whether the reference on the left is of the type on the right. So list.get(i) instanceof IdNamePair checks to see if that entry in the List is actually an IdNamePair object.

If it is, your code casts it to an IdNamePair - so the instanceof is letting you check whether that cast is actually going to work. It looks as if you've got a List that contains objects of two different types*, so every time you get a value out you need to check which type it is.

* And I have to say, that's almost certainly not a good idea. That much casting is usually an indicator that there's a flaw in the design.
Aggarwal Arpit
Ranch Hand

Joined: Mar 04, 2012
Posts: 86
Thanks for explaining it in detail.....
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

Listen to what Matthew said, this is BAD CODE.

Junilu - [How to Ask Questions] [How to Answer Questions]
I agree. Here's the link:
subject: List instanceof class
It's not a secret anymore!