我是靠谱客的博主 懵懂宝马,最近开发中收集的这篇文章主要介绍java int 转 object,如何将Object转换为int,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

解决方案

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 :

On the same topic :

最后

以上就是懵懂宝马为你收集整理的java int 转 object,如何将Object转换为int的全部内容,希望文章能够帮你解决java int 转 object,如何将Object转换为int所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部