java integer 转string,为什么不能在Java中将Integer转换为String?

博客内容探讨了一个Java编程中遇到的ClassCastException,即尝试将Integer对象强制转换为String时出现的错误。文章解释了这是因为Integer和String不在同一继承层次上,不能直接转换,并提供了正确的转换方法,如使用`String.valueOf(integer)`或`Integer.toString()`。
摘要由CSDN通过智能技术生成

I found some strange exception:

java.lang.ClassCastException: java.lang.Integer

cannot be cast to java.lang.String

How it can be possible? Each object can be casted to String, doesn't it?

The code is:

String myString = (String) myIntegerObject;

Thanks.

解决方案

Why this is not possible:

Because String and Integer are not in the same Object hierarchy.

Object

/ \

/ \

String Integer

The casting which you are trying, works only if they are in the same hierarchy, e.g.

Object

/

/

A

/

/

B

In this case, (A) objB or (Object) objB or (Object) objA will work.

Hence as others have mentioned already, to convert an integer to string use:

String.valueOf(integer), or Integer.toString(integer) for primitive,

or

Integer.toString() for the object.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值