java hashmap 的 get() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/764837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:40:31  来源:igfitidea点击:

the get() function for java hashmaps

javaobjectreferencehashmap

提问by Zain Riz

I've declared the following hashmap:

我已经声明了以下哈希图:

HashMap<Integer, Hive> hives

Where Hive is an object.

Hive 是一个对象。

If I call "hives.get(2)" will it return a copy of the object Hive at that location or a reference to it?

如果我调用“hives.get(2)”,它会返回该位置的 Hive 对象的副本还是对它的引用?

My goal is to modify the Hive object at that location. If it returns the reference, I can just modify the returned hive and be done. However, if a copy gets returned then I'll have to put that copy back into the hashmap.

我的目标是修改该位置的 Hive 对象。如果它返回引用,我可以修改返回的配置单元并完成。但是,如果返回副本,则必须将该副本放回哈希映射中。

Sorry for the simple question. I tried looking around for a solution, but everywhere I looked it simply said the value would be returned, it didn't say if it would be a copy of the value or a reference to it.

对不起,这个简单的问题。我尝试四处寻找解决方案,但在我所看到的任何地方,它都只是说将返回该值,而没有说明它是该值的副本还是对该值的引用。

Thanks, Zain

谢谢,赞恩

回答by jfclavette

It returns a reference. You can pretty much assume this is the case unless otherwise specified.

它返回一个引用。除非另有说明,否则您几乎可以假设是这种情况。

回答by hbw

You will get a reference to it—Java objects are always passed by reference.

您将获得对它的引用——Java 对象总是通过引用传递。

回答by Scott M.

in java everything except byte, short, int, long, float, double, and char is passed by reference. the above types are the only primitive types in java, and are passed by value. If you want a copy by value you need to make your own method in the object that will return a deep copy of itself.

在 Java 中,除了 byte、short、int、long、float、double 和 char 之外的所有内容都是通过引用传递的。以上类型是java中唯一的原始类型,都是按值传递的。如果您想要按值复制,您需要在对象中创建自己的方法,该方法将返回自身的深层副本。