0

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?

Arrigo Pierotti
  • 203
  • 4
  • 10
  • 18

2 Answers2

4

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.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

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().

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79