Skip to main content
  1. About
  2. For Teams
Asked
Viewed 20k times
18

I've declared the following hashmap:

HashMap<Integer, Hive> hives

Where Hive is an object.

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

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.

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

3 Answers 3

25

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

Sign up to request clarification or add additional context in comments.

Comments

9

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

2 Comments

Okay, since you can't dereference object pointers in Java, I guess it's technically pass-by-value. But saying that would be totally misleading for the person who asked the question. It seems like kind of a nitpicky argument, in my opinion.
Everything in Java is pass by value. You pass around object references by value. If you passed the object reference by reference, then you could change the value of the reference. Therefoer, a called method could change the value of the reference in the callee method. Java does not support this, because it is pass by value only.
7

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.

2 Comments

ok. java is strictly pass by value, however what it passes is a reference to the object.
It's a key difference -- if Java were really "pass by reference" then if you said myHashMap.get(2)=null then the original object passed in to the HashMap with key 2 would now be null. But it won't. Yes, the whole "pass by value where the value is actually a reference" is confusing, but it's important to actually understand it.

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.