Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapping from Integer to int possible?

 
Ann Smith
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After extracting the first object contained in an ArrayList, it is inevitably of type Object. I think I can cast this to an Integer (although I havent tested it, I may get a ClassCastError), and then I tried wrapping it as an int but apparently that's impossible. Any way's around this?
 
Chris Johnston
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not totally sure what you are doing here, but an int isn't an object so it can't wrap anything.

You receive an Object and you want to extract an int from it?

Should go something like this:

receive your Object
check to see if it is an instanceof Integer
parse out the int that is contained inside
 
Ann Smith
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I realized all I had to do was use the intValue() method for Integer. I think hopefully this will solve the problem. But this is awesome because I was just looking for the method instanceOf. Where does that method come from? Which class? I need to find in stances of the same int in a List.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instanceof is not a method it is an operator like + - * / %.

It allows you to test if an Object is of a certain type.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are sure that the first object in the List always is an Integer, you don't need instanceof.

Use instanceof if you could get different type of objects and want to do different things with them based on their type *and* you can't use polymorphism to do it.
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you using JDK5? If so, you can avoid all of this by making your ArrayList an ArrayList<Integer>. Also, JDK5 will "autobox" (and "autounbox") your primitives for you, so you can avoid all of the intValue() stuff, too.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic