How to cast an Object to an int
If you're sure that this object is an Integer
:
int i = (Integer) object;
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
Beware, it can throw a ClassCastException
if your object isn't an Integer
and a NullPointerException
if your object is null
.
This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
int
is a primitive so it can't be stored as an Object
, the only way is to have an int
considered/boxed as an Integer
then stored as an Object
.
If your object is a String
, then you can use the Integer.valueOf()
method to convert it into a simple int :
int i = Integer.valueOf((String) object);
It can throw a NumberFormatException
if your object isn't really a String
with an integer as content.
Resources :
- Oracle.com - Autoboxing
- Oracle.com - Primitive Data types
On the same topic :
- Java: What's the difference between autoboxing and casting?
- Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
- Convert Object into primitive int
How to cast Object[] to int[] java?
As you have acknowledged in your question, int
does not extend Object
so the cast makes no sense and the compiler correctly complains.
Likely the safest and easiest way to achieve this is:
Object[] objects = {1, 2, 3, 4};
int[] ints = Arrays.stream(objects).mapToInt(o -> (int)o).toArray();
Not particularly elegant, but then again neither is storing an array of integers in an array of Object
:-)
How can i convert an object to an int in Java?
Integer.parseInt()
expects a String
. You can use
Integer.parseInt(f.toString())
and override the toString()
method in your class.
Cast a Java Object to Integer
What you want is:
int ei = ((Integer) entry.getIdentifier()).intValue();
Better way to cast object to int
You have several options:
(int)
— Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.int.Parse()/int.TryParse()
— For converting from a string of unknown format.int.ParseExact()/int.TryParseExact()
— For converting from a string in a specific formatConvert.ToInt32()
— For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.as int?
— Note the "?". Theas
operator is only for reference types, and so I used "?" to signify aNullable<int>
. The "as
" operator works likeConvert.To____()
, but thinkTryParse()
rather thanParse()
: it returnsnull
rather than throwing an exception if the conversion fails.
Of these, I would prefer (int)
if the object really is just a boxed integer. Otherwise use Convert.ToInt32()
in this case.
Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short)
might work instead, and for recommending you check your debugger to find out the actual runtime type.
Cannot cast from object to int
request.getAttribute
returns Object. You cannot cast Object to a primitive type int
. But you may cast it to Integer
.
Casting Double object to int
Double.intValue()
is the provided method that does that conversion.
Pandas: convert dtype 'object' to int
Documenting the answer that worked for me based on the comment by @piRSquared.
I needed to convert to a string first, then an integer.
>>> df['purchase'].astype(str).astype(int)
How do I cast an object to an int in a Converter?
Both Convert.ToInt32
or Int32.Parse
should work... If they don't, then the value is definitely not an int ;)
Try to put a breakpoint in your converter to watch the value, it might show you why it doesn't work
Related Topics
@Onetomany List<> VS Set<> Difference
When Should an Illegalargumentexception Be Thrown
Does Java Have Any Mechanism for a Vm to Trace Method Calls on Itself, Without Using Javaagent, etc
How to Get Method Parameter Names in Java 8 Using Reflection
Handling Datetime Values 0000-00-00 00:00:00 in Jdbc
Java Benchmarking - Why Is the Second Loop Faster
Better Way to Create Aes Keys Than Seeding Securerandom
How to Send Java.Util.Logging to Log4J
How to Configure Httponly Cookies in Tomcat/Java Webapps
When to Use a Constructor and When to Use Getinstance() Method (Static Factory Methods)
How to Convert a Binary String to a Base 10 Integer in Java
Block()/Blockfirst()/Blocklast() Are Blocking Error When Calling Bodytomono After Exchange()