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

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

问题描述

我有一个 HashMap:

I have a HashMap:

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

首先打印1000,第二次打印1000,值不变.为什么 Java 是按值而不是按引用返回整数?

First it prints 1000, and the second time it's printing 1000, the value does not change. Why is Java returning the Integer by value and not by reference?

推荐答案

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

The get method returns a copy of the reference to the stored integer...

为存储此副本的变量分配一个新值以指向值 10不会改变映射中的引用.

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

如果您可以执行 balance.setValue(10),它会起作用,但是由于 Integer 是一个不可变的类,所以这不是一个选项.

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 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天全站免登陆