問題描述
我發現了一些奇怪的異常:
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?
代碼是:
String myString = (String) myIntegerObject;
謝謝.
推薦答案
為什么這是不可能的:
因為 String 和 Integer 不在同一個 Object 層次結構中.
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
在這種情況下,(A) objB
或 (Object) objB
或 (Object) objA
將起作用.
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)
,或 Integer.toString(integer)
表示原語,
或
Integer.toString()
用于對象.
這篇關于為什么不能在 Java 中將 Integer 轉換為 String?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!