Zain Riz
Zain Riz

Reputation: 205

the get() function for java hashmaps

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

Upvotes: 18

Views: 20134

Answers (3)

Scott M.
Scott M.

Reputation: 7347

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.

Upvotes: 7

hbw
hbw

Reputation: 15750

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

Upvotes: 9

jfclavette
jfclavette

Reputation: 3489

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

Upvotes: 25

Related Questions