• 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

This question is about AutoBoxing feature in java

 
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,

This question is about AutoBoxing, here i am adding some int primitive into ArrayList .
The problem is when i am retriving , it is expecting an Object when i say list.get(1);

The question i am asking is that , If we add a primitive type into a DataStructure , whether Autoboxing feature implicitly converts a primitive into a Object ??



 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It does. Your problem is that your ArrayList is a raw ArrayList; the compiler doesn't know that it contains only Integer objects. If you change the declaration to the compiler knows that this list will contain only Integer objects, and therefore get(1) will return an Integer. If you are absolutely certain that it does not return null you can use auto unboxing to turn that back into an int:
As I said, only do this if you are certain that the Integer is not null. If it is, the auto unboxing will throw a NullPointerException.

1) it is better to declare as interfaces or abstract classes. If you don't know why search around in Beginning Java and Java in General for the answer.
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much .

Your code helped me .
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic