autoboxing在java中不起作用

red*_*ddy 2 java autoboxing

我有以下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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*esB 5

23是int类型,而不是Integer.它是原始的,而不是对象.

Integer.valueOf(23).toString();
Run Code Online (Sandbox Code Playgroud)

这比使用构造函数更好,因为valueOf方法将使用-128到127范围内的缓存值.

你可能想参考这个:http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html


Bob*_*oss 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您将该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.
Run Code Online (Sandbox Code Playgroud)