Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

List instanceof class

 
Aggarwal Arpit
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for explaining it in detail.....
 
Junilu Lacar
Bartender
Posts: 7482
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Listen to what Matthew said, this is BAD CODE.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic