Java是通过引用还是按值返回? [英] Does Java return by reference or by value

查看:134
本文介绍了Java是通过引用还是按值返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

解决方案

get 方法返回对存储整数的引用的一个副本 ...

为存储此副本的变量赋值一个新值,指向值 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); 


I have a HashMap:

private HashMap<String, Integer> cardNumberAndCode_ = new HashMap<String, Integer>();

And later I do this:

Integer balance = cardNumberBalance_.get(cardNumber);
System.out.println(balance);
balance = 10;
Integer newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance);

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 get method returns a copy of the reference to the stored integer...

Assigning a new value to the variable storing this copy to, point to the value 10 will not change the reference in the map.

It would work if you could do balance.setValue(10), but since Integer is an immutable class, this is not an option.

If you want the changes to take affect in the map, you'll have to wrap the the balance in a (mutable) class:

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());

But you would probably want to do something like this instead:

cardNumberBalance_.put(cardNumber, 10);

这篇关于Java是通过引用还是按值返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆