Java Object Reference Passing Vs. C++ Memory Reference Passing -


i understand java pass value, , when passing objects functions, pass value of reference function/outside scope. know, too, cannot alter object inside function. being understood, can alter object reference stored in 2 different data structures in c/c++?

for example

class objectreferences {     static hashmap<string, object> map1 = new hashmap<string, object>();     static hashmap<string, object> map2 = new hashmap<string, object>();      public static void addtoboth(object o) {         map1.put("one",o);         map2.put("two",o);     }      public static void main(string[] args) {         stringbuffer foo = new stringbuffer("wat");         addtoboth(foo);         map1.get("one").append("er");         system.out.println(map2.get("two").tostring());     } } 

by reasoning should print out "water". can explain why or not work in mystical land of java?

ok. let's first correct code works (in java 7+), , run it:

import java.util.hashmap;  public class objectreferences {     static hashmap<string, stringbuffer> map1 = new hashmap<>();     static hashmap<string, stringbuffer> map2 = new hashmap<>();      public static void addtoboth(stringbuffer sb) {         map1.put("one",sb);         map2.put("two",sb);     }      public static void main(string[] args) {         stringbuffer foo = new stringbuffer("wat");         addtoboth(foo);         map1.get("one").append("er");         system.out.println(map2.get("two").tostring());     } } 

this prints water, expected. why? because sb in addtoboth method references exact same object (the 1 , stringbuffer first referenced foo), appending , getting same object later return - same object. java doesn't magically copy object internals (unless clone objects, that's story).

hope helps.

p.s. had written code , close running yourself. there further background question? seems have answered yourself.


Comments