1

If I pass a map over to a class I've made, if that class then modifies the map, would it change the map in the main method that passed it originally?

Does the second instance point to the same map?

sailboatlie
  • 346
  • 1
  • 6
  • 18

4 Answers4

1

Yes, the caller will see the changes that the callee makes.

Does the second instance point to the same map?

There is no second instance (unless you explicitly make a copy of the map). What you have is two references to the same instance.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Yes. Your original map reference (not a copy map object) is passed and any change made in the map in other class will reflect in the map in the main method as well.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • If the I were to then create a new map equal to the original map that was passed in. Would that new reference still point to the original? – sailboatlie Dec 05 '12 at 21:12
  • @sailboatlie Not sure what exactly you mean by `new map` but if you are creating a new map (new HashMap() etc.) and copying the elements then it will not. – Yogendra Singh Dec 05 '12 at 21:17
  • @Singh Yes, that's what I meant. Thanks for the answer! – sailboatlie Dec 05 '12 at 21:24
0

Yes, you're passing a reference value.

It seems like this would be drop-dead simple to prove experimentally, no?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

If the map is passed to any method, this method can change the content of the map, which is then visible for all, that acces the map. However that method can not change the map object itself, e.g by replacing the map with another one.

AlexWien
  • 28,470
  • 6
  • 53
  • 83