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
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.
Cast a Java Object to Integer
What you want is:
int ei = ((Integer) entry.getIdentifier()).intValue();
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.
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
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
.
python cast object to int
Try to use
...
def __int__(self):
return self.score
...
test = MyObject(0, 0, 10, 0, 0)
print 10+int(test)
# Will output: 20
in your MyObject class definition.
Related Topics
Jquery Ajax Calls to Web Service Seem to Be Synchronous
How to Invoke Scripts Work in Mshtml
Datagrid Shows Path of Image Instead of Image Itself
Wrap Properties with Cdata Section - Xml Serialization C#
How to Re-Write a SQL Query as a Parameterized Query
Enterprise Library Unity VS Other Ioc Containers
How to Unapply a Migration in ASP.NET Core with Ef Core
Test If Object Implements Interface
What Difference Is There Between Webclient and Httpwebrequest Classes in .Net
Http Post Returns Error: 417 "Expectation Failed."
When Should I Choose Inheritance Over an Interface When Designing C# Class Libraries
Better Way to Cast Object to Int
Restsharp Simple Complete Example
Entity Framework - Add Navigation Property Manually
How to Create a Temp File with a Specific Extension with .Net
How to Create Roles in ASP.NET Core and Assign Them to Users