Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 635
Zain Riz Avatar asked Apr 19 '09 04:04

Zain Riz


People also ask

What does get function do in HashMap?

The get() method returns the value corresponding to the specified key in the hashmap.

Are there Hashmaps in Java?

HashMap<K, V> is a part of Java's collection since Java 1.2. This class is found in java. util package. It provides the basic implementation of the Map interface of Java.

How does Hashmaps work in Java?

HashMap uses multiple buckets and each bucket points to a Singly Linked List where the entries (nodes) are stored. Once the bucket is identified by the hash function using hashcode, then hashCode is used to check if there is already a key with the same hashCode or not in the bucket(singly linked list).

What is put and get in HashMap?

HashMap. put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value.


1 Answers

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

like image 52
jfclavette Avatar answered Oct 14 '22 12:10

jfclavette