0

I'm wondering if these two statements are equivalent:

Map<String, List<String>> nodeToLinkMap = new HashMap<String, List<String>>();
... 
// (assuming the map has something in it for this key)
List<String> links = nodeToLinkMap.get(node);
links.add(link);
nodeToLinkMap.put(node, links);

and

Map<String, List<String>> nodeToLinkMap = new HashMap<String, List<String>>();
... 
// (assuming the map has something in it for this key)
nodeToLinkMap.get(node).add(link));

Is it the same pointer or does a copy get made?

2
  • 3
    Consider using a Guava Multimap instead of rolling your own.
    – Matt Ball
    Commented Jul 1, 2013 at 22:26
  • Java doesn't have pointers, it has references and these references are copied, not the objects they refer to. There is not implicit copy constructor in Java. Commented Jul 1, 2013 at 22:26

2 Answers 2

4

Both statements will accomplish the same thing.

Note that when you call

nodeToLinkMap.put(node, links);

in the first snippet, you're actually replacing the value that node maps to with itself.

So, you could shorten the first part to

Map<String, List<String>> nodeToLinkMap = new HashMap<String, List<String>>();
... 
// (assuming the map has something in it for this key)
List<String> links = nodeToLinkMap.get(node);
links.add(link);
3

Is it the same pointer or does a copy get made?

First of all, there is no such thing as pointers in Java. It's called reference.

List<String> links = nodeToLinkMap.get(node);

In the above code, you are simply creating a new reference to the list stored in the map. It does not create a copy of the list itself. So, whatever you add or remove from this list gets reflected in the list stored in map. You don't need to put the list back into the map.

So, you can remove this line from your 1st code:

nodeToLinkMap.put(node, links);  // Not needed.

2nd code is fine. But it might not look pleasant, if you are going to do too much modification in your list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.