我如何在java中将对象转换为int型?
当前回答
答:
int i = ( Integer ) yourObject;
如果你的对象已经是一个整数,它将顺利运行。即:
Object yourObject = 1;
// cast here
or
Object yourObject = new Integer(1);
// cast here
etc.
如果你的对象是其他类型的对象,你需要先将它(如果可能的话)转换为int类型:
String s = "1";
Object yourObject = Integer.parseInt(s);
// cast here
Or
String s = "1";
Object yourObject = Integer.valueOf( s );
// cast here
其他回答
如果你的意思是将String转换为int,请使用Integer.valueOf("123")。
你不能将大多数其他对象强制转换为int型,因为它们没有int值。例如,XmlDocument没有int值。
不可能做到。int不是一个对象,它是一个基本类型。你可以将它转换为Integer,然后获取int。
Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class
int num = i; //Java 1.5 or higher
int i = (Integer) object; //Type is Integer.
int i = Integer.parseInt((String)object); //Type is String.
必须将其强制转换为Integer (int的包装类)。然后,您可以使用Integer的intValue()方法来获取内部整型。
我们可以使用下面的代码在Java中转换一个对象为Integer。
int value = Integer.parseInt(object.toString());
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 向对象数组添加属性
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder