如何将对象转换为java中的int? [英] How to cast an Object to an int in java?

查看:138
本文介绍了如何将对象转换为java中的int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将对象转换为int?

How can I cast an Object to an int in java?

推荐答案

如果您确定此对象是 Integer

int i = (Integer) object;

或者,从Java 7开始,你可以写成:

Or, starting from Java 7, you can equivalently write:

int i = (int) object;

注意,它可以抛出 ClassCastException 如果您的对象不是 Integer 如果你的对象是 null

Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.

这样你就可以假设NullPointerException 你的对象是一个整数(包装的int),你unbox它成一个int。

This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.

int 原语,所以它不能存储为对象,唯一的办法是有一个 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.

如果你的对象是 String ,那么你可以使用 Integer.valueOf() 方法将其转换为一个简单的int:

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);

它可以抛出 NumberFormatException 如果您的对象不是真的 String 以整数作为内容。

It can throw a NumberFormatException if your object isn't really a String with an integer as content.

strong>

Resources :

  • Oracle.com - Autoboxing
  • Oracle.com - Primitive Data types

同一主题:

  • 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

这篇关于如何将对象转换为java中的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆