2

我有以下Java类:

public class HelloWorld{

    public static void main(String []args){

        String s = 23.toString();//compilation error is ';' expected
        s = s + "raju";
        System.out.println(s);
    }
}

但根据自动装箱 23.toString() 必须转换为 new Integer(23).toString() 并执行该行。那么为什么我仍然收到编译错误?

4

6 回答 6

5

23 is of type int, not Integer. It is a primitive, not an object.

Integer.valueOf(23).toString();

This is better than using the constructor as the valueOf method will use cache values in the range -128 to 127.

You probably want to refer to this: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

于 2013-11-06T13:23:28.190 回答
5

您对自动装箱何时起作用感到困惑。在这种情况下,您尝试在普通的旧数据类型(int)上使用 Object 方法。

相反,请尝试Integer.valueof()

public class HelloWorld{

    public static void main(String []args){
        // String s = 23.toString() will not work since a int POD type does not
        // have a toString() method.
        // Integer.valueOf(23) gets us an Integer Object.  Now we can 
        // call its toString method
        String s=Integer.valueof(23).toString();
        s=s+"raju";
        System.out.println(s);
    }
}

如果您将该 int 传递给期望 Integer 作为参数的方法,则自动装箱将起作用。例如:

List<Integer> intList = new ArrayList<>();
// Autoboxing will silently create an Integer here and add it to the list
intList.add(23);
// In this example, you've done the work that autoboxing would do for you
intList.add(Integer.valueof(24));
// At this point, the list has two Integers, 
// one equivalent to 23, one equivalent to 24.
于 2013-11-06T13:25:27.013 回答
3

23 is int primitive, replace with new Integer(23) (wrapper on primitive)

于 2013-11-06T13:23:21.520 回答
1

它不是自动装箱你正在做的事情。看看这里

这应该有效:

public class HelloWorld{

    public static void main(String []args){
        Integer i=23;//autoboxing int to Integer
        String s=i.toString();
        System.out.println(s);
    }
}
于 2013-11-06T13:25:55.950 回答
1

你写的是类型类型转换,而不是自动装箱。

要转换为字符串,您可以执行以下操作:

String s="23";

或者

Integer i = new Integer(23);
s=i.toString()+"raju";

自动装箱是自动将原语转换intInteger

Integer i = 23; //Old variant Integer i = new Integer(23);
int a = i; //Old variant int i = (int) someInteger;
于 2013-11-06T13:29:34.503 回答
0

它不起作用,因为 Java 不允许您取消对原语的引用。自动装箱适用于诸如赋值和将原语传递给方法而不是对象之类的事情。

于 2013-11-06T13:29:12.763 回答