简体   繁体   English

如何在 Java 中将 Object 类型转换为 int 类型?

[英]How can I convert an Object type to a int type in Java?

I'm looking for a way to convert a Object type (as in the wildcard type which can store many different types) to an int type.我正在寻找一种将Object类型(如可以存储许多不同类型的通配符类型)转换为int类型的方法。 In all of my searching I have not found an answer to this question on the site.在我所有的搜索中,我都没有在网站上找到这个问题的答案。

I have a Object[] array which stores only integers and I need to perform some math using one of the integers.我有一个Object[]数组,它只存储整数,我需要使用其中一个整数执行一些数学运算。 For example int result = array[3] + 2;例如int result = array[3] + 2; . . This arithmetic won't work unless I can cast/convert that Object to an int .除非我可以将该Object强制转换/转换为int ,否则此算术将不起作用。

The others that say Integer[] and int[] are the solutions to the question is very true when only numbers will be added in the array.其他人说Integer[]int[]是问题的解决方案,当数组中只添加数字时,这是非常正确的。 But, In some cases, there are requirements that we should follow.但是,在某些情况下,我们应该遵循一些要求。 So Object that contains number can be casted to Integer and unbox it to int is more likely what the OP needs.因此,包含数字的Object可以转换为Integer并将其拆箱为int更可能是 OP 需要的。

如果你自己定义对象数组,我想你可以使用int数组,如果其他方法返回这个数据类型,你可以转换为int,但你需要检查对象数组元素是否不是

I have a Object[] array which stores only integers我有一个只存储整数的Object[]数组

Solution: don't.解决办法:不要。 Use Integer[] , or better still int[] , as @dave has already told you.使用Integer[] ,或者更好的是int[] ,正如@dave 已经告诉你的那样。

The suggestion to cast the objects twice is inefficient and error-prone.将对象投射两次的建议效率低下且容易出错。

Don't cause downstream problems for yourself by weak typing.不要通过弱类型给自己造成下游问题。

As a side benefit, if your assertion that it stores only integers turns out to be untrue, you will now find out at compile time, instead of at runtime.作为附带的好处,如果您关于它只存储整数的断言被证明是不正确的,您现在将在编译时发现,而不是在运行时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM