且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将对象转换为 int

更新时间:2023-02-14 12:20:53

如果你确定这个对象是一个 Integer :

If you're sure that this object is an Integer :

int i = (Integer) object;

或者,从 Java 7 开始,您可以等效地编写:

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

int i = (int) object;

当心,它可能会抛出一个 ClassCastException 如果您的对象不是 IntegerNullPointerException 如果您的对象是 null.

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 是一个原语,所以它不能存储为 Object,唯一的方法是考虑/装箱一个 int作为 Integer 然后存储为 Object.

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.

资源:

关于同一主题: