When i use the V get(Object key)
method in a Java TreeMap<K, V>
I obtain a brand new copy of the value connected to the key I insert in the V get(Object key)
method, or I got a "reference" to the value V right inside the TreeMap
?

- 203
- 4
- 10
- 18
-
2The value _is_ the reference. – Sotirios Delimanolis Feb 17 '15 at 16:24
-
A bit of a shameless plug, but if the difference between a reference and an object confuses you, maybe check out http://stackoverflow.com/questions/9224517/what-is-a-class-reference-and-an-object. – yshavit Feb 17 '15 at 16:45
-
The whole problem was if the get method would gave me the object inside the TreeMap or a new object not in the TreeMap :-) Problem solved below – Arrigo Pierotti Feb 17 '15 at 16:52
2 Answers
The Map#get()
returns a reference but the Map#put()
method too stores a reference only. The actual Object
lives on the heap. In fact, the TreeMap
works with Entry<K,V>
references and the actual Entry
objects on the heap then point to the actual key and value objects on the heap again.

- 51,095
- 9
- 76
- 89
-
So with the get method I'll be able to modify the very object I put in before? – Arrigo Pierotti Feb 17 '15 at 16:34
In general, Java's standard collections do not copy the values they are given. If you notice, the values are not constrained to be Cloneable
(and even if they were, because of the weirdness of Cloneable
, it wouldn't ensure that they were actually clonable). And there is no other way for a copy to be created (since you cannot run new
on a generic type variable).
Therefore, they have to make do with the references they were given, and that's what you get when you retrieve them with get()
.

- 33,993
- 7
- 53
- 79