Java是通过引用还是按值返回? [英] Does Java return by reference or by value
问题描述
我有一个HashMap:
private HashMap< String,Integer> cardNumberAndCode_ = new HashMap< String,Integer>();
后来我这样做:
整数余额= cardNumberBalance_.get(cardNumber);
System.out.println(余额);
余额= 10;
整数newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance);
首先打印1000,第二次打印1000时,值不变。为什么java按值返回Integer而不是通过引用返回Integer?
为存储此副本的变量赋值一个新值,指向值 如果你可以做 如果您想让更改在地图中生效,您必须将余额包装到(可变)类中: 但是您可能想要这样做: I have a HashMap: And later I do this: First its prints 1000, and the second time its printing 1000, the value is not change. Why are java returning the Integer by value and not by reference? The Assigning a new value to the variable storing this copy to, point to the value It would work if you could do If you want the changes to take affect in the map, you'll have to wrap the the balance in a (mutable) class: But you would probably want to do something like this instead:
这篇关于Java是通过引用还是按值返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
10
will not 更改地图中的引用。
balance.setValue(10)
,它会起作用,但是因为 Integer
是一个不可变类,所以而不是一个选项。
class Balance {
int balance;
...
}
余额余额= cardNumberBalance_.get(cardNumber);
System.out.println(balance.getBalance());
balance.setBalance(10);
余额newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance.getBalance());
cardNumberBalance_.put(cardNumber,10);
private HashMap<String, Integer> cardNumberAndCode_ = new HashMap<String, Integer>();
Integer balance = cardNumberBalance_.get(cardNumber);
System.out.println(balance);
balance = 10;
Integer newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance);
get
method returns a copy of the reference to the stored integer...10
will not change the reference in the map.balance.setValue(10)
, but since Integer
is an immutable class, this is not an option.class Balance {
int balance;
...
}
Balance balance = cardNumberBalance_.get(cardNumber);
System.out.println(balance.getBalance());
balance.setBalance(10);
Balance newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance.getBalance());
cardNumberBalance_.put(cardNumber, 10);