1

I have two HashMaps defined as follows:

HashMap EventTable = new HashMap();
HashMap MainTable = new HashMap ();

Now, suppose I insert some data into EventTable:

EventTable.put("name", "Test Event Name");

Then, suppose we insert the EventTable into the MainTable:

MainTable.put("table", EventTable);

and then print out MainTable:

{table={name=Test Event Name}}

Now if I modify Event Table as follows:

 EventTable.put("more names", "More test events");

This changes the MainTable as well:

{table={more names=More test events, name=Test Event Name}}

So obviously, EventTable is being passed by reference to MainTable.

I don't understand why EventTable is being passed by reference.

Ideally I would like to reuse the EventTable HashMap to create other entries, while retaining my old entries, so I would like to pass EventTable by value.

EDIT:

Forgot to mention this in the main question, but when I add a String to the MainTable, that does not change when I modify the string afterwards. So how is the behavior is different for the String?

Chaos
  • 11,213
  • 14
  • 42
  • 69
  • 2
    http://stackoverflow.com/questions/40480/is-java-pass-by-reference – assylias Aug 06 '13 at 23:18
  • EventTable is not passed by reference - if you reassign EventTable with `EventTable = new HashMap` after having inserted it in MainTable, it won't change the content of MainTable. – assylias Aug 06 '13 at 23:24
  • 2
    Ok, I think i get it. EventTable is still pointing to the same location as the HashMap entry, so when I reassign Event Table, it doesn't affect the HashMap entry anymore, am I right? – Chaos Aug 06 '13 at 23:28

3 Answers3

5

Although I would never use raw types and follow the Java naming conventions, you can do something like this to get your desired behavior:

mainTable.put("table", new HashMap(eventTable));

To address your edit: Strings are immutable in Java.

jlordo
  • 37,490
  • 6
  • 58
  • 83
3

as in @assylias said, parameters passed by value.

here HashMap can not copy the date because it could be anything. but you can create a new HashMap by its constructor.

HashMap newHashMap= new HashMap(oldHashMap);
Hossein Nasr
  • 1,436
  • 2
  • 20
  • 40
3

It is because, even though Java passes all arguments by value, when you pass an object, you are really passing an object reference. if you were to set EventTable to a new Hashmap, the one you passed in to MainTable would not be changed. This article may help clear things up: http://javadude.com/articles/passbyvalue.htm

Jaime Morales
  • 369
  • 1
  • 4