我知道Java是按引用传递的,但只适用于Java对象。但为什么不适用于Java包装类?像Integer、Float、Double这样的包装类是按引用传递还是按值传递的?因为每当我将这些类的对象传递到方法中并更改一些值时,但在该方法之外,我没有获得更新后的值。
我知道Java是按引用传递的,但只适用于Java对象。但为什么不适用于Java包装类?像Integer、Float、Double这样的包装类是按引用传递还是按值传递的?因为每当我将这些类的对象传递到方法中并更改一些值时,但在该方法之外,我没有获得更新后的值。
除了“按值传递”讨论之外,在Java中所有的包装类都是不可变的。它们复制了基本类型的行为。你需要返回最新的值才能看到更改。
public static void main(String[] args) {
Integer i = 5;
display(i);
System.out.println(i);
}
private static void display(Integer i) {
i = 10;
}
The reason why i will not be updated because i=10 will use autoboxing here and it will be similar to i = new Integer(10)
Since i is pointing to a new memory address this change will not appear in main method