• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

List instanceof class

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 375
1
Python Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for explaining it in detail.....
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Listen to what Matthew said, this is BAD CODE.
reply
    Bookmark Topic Watch Topic
  • New Topic