views:

848

answers:

3

Hi,

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

+6  A: 

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

jfclavette
+4  A: 

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

htw
-- Java is pass by value. http://javadude.com/articles/passbyvalue.htm
cherouvim
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.
htw
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.
A_M
+2  A: 

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.

Scott M.
-- Java is pass by value. http://javadude.com/articles/passbyvalue.htm
cherouvim
ok. java is strictly pass by value, however what it passes is a reference to the object.
Scott M.
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.
JacobM