Why cannot cast Integer to String in java?

后端 未结 11 2560
时光取名叫无心
时光取名叫无心 2020-11-29 18:00

I found some strange exception:

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

How it can be possible

11条回答
  •  清酒与你
    2020-11-29 18:42

    You can't cast explicitly anything to a String that isn't a String. You should use either:

    "" + myInt;
    

    or:

    Integer.toString(myInt);
    

    or:

    String.valueOf(myInt);
    

    I prefer the second form, but I think it's personal choice.

    Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

    Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

提交回复
热议问题