autoboxing在java中不起作用

时间:2013-11-06 13:21:17

标签: 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);
    }
}

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

6 个答案:

答案 0 :(得分:5)

23是int类型,而不是Integer。它是一个原始的,而不是一个对象。

Integer.valueOf(23).toString();

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

您可能想要参考:http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

答案 1 :(得分: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作为参数的方法,则Autoboxing将起作用。例如:

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.

答案 2 :(得分:3)

23int原语,替换为new Integer(23)(原语包装器)

答案 3 :(得分:1)

这不是自动装箱你正在做什么。看看here

这应该有效:

public class HelloWorld{

    public static void main(String []args){
        Integer i=23;//autoboxing int to Integer
        String s=i.toString();
        System.out.println(s);
    }
}

答案 4 :(得分:1)

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

要转换为字符串,您可以执行下一步:

String s="23";

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

自动装箱是将原始int自动转换为Integer

Integer i = 23; //Old variant Integer i = new Integer(23);
int a = i; //Old variant int i = (int) someInteger;

答案 5 :(得分:0)

它不起作用,因为Java不会让你取消引用原语。自动装箱适用于分配和将基元传递给方法来代替对象。