Why cannot cast Integer to String in java?

后端 未结 11 2474
时光取名叫无心
时光取名叫无心 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:37

    Use String.valueOf(integer).

    It returns a string representation of integer.

    0 讨论(0)
  • 2020-11-29 18:41

    Casting is different than converting in Java, to use informal terminology.

    Casting an object means that object already is what you're casting it to, and you're just telling the compiler about it. For instance, if I have a Foo reference that I know is a FooSubclass instance, then (FooSubclass)Foo tells the compiler, "don't change the instance, just know that it's actually a FooSubclass.

    On the other hand, an Integer is not a String, although (as you point out) there are methods for getting a String that represents an Integer. Since no no instance of Integer can ever be a String, you can't cast Integer to String.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 18:43

    For int types use:

    int myInteger = 1;
    String myString = Integer.toString(myInteger);
    

    For Integer types use:

    Integer myIntegerObject = new Integer(1);
    String myString = myIntegerObject.toString();
    
    0 讨论(0)
  • 2020-11-29 18:45

    No. Every object can be casted to an java.lang.Object, not a String. If you want a string representation of whatever object, you have to invoke the toString() method; this is not the same as casting the object to a String.

    0 讨论(0)
  • 2020-11-29 18:50

    No, Integer and String are different types. To convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object.

    0 讨论(0)
提交回复
热议问题