为什么不能在java中将整数转换为字符串?

2022-08-31 09:46:29

我发现了一些奇怪的例外:

java.lang.ClassCastException: java.lang.Integer 
 cannot be cast to java.lang.String

怎么可能?每个对象都可以转换为 String,不是吗?

代码是:

String myString = (String) myIntegerObject;

谢谢。


答案 1

为什么这是不可能的:

因为字符串和整数不在同一个对象层次结构中。

      Object
     /      \
    /        \
String     Integer

您正在尝试的选角仅在它们处于同一层次结构中时才有效,例如

      Object
     /
    /
   A
  /
 /
B

在这种情况下,或或将起作用。(A) objB(Object) objB(Object) objA

因此,正如其他人已经提到的那样,要将整数转换为字符串,请使用:

String.valueOf(integer),或者对于基元,Integer.toString(integer)

Integer.toString()作为对象。


答案 2

否,并且是不同的类型。要将整数转换为字符串,请使用: ,或者对于基元或对象。IntegerStringString.valueOf(integer)Integer.toString(integer)Integer.toString()