40

If I create a new HashMap and a new List, and then place the List inside the Hashmap with some arbitrary key and then later call List.clear() will it affect what I've placed inside the HashMap?

The deeper question here being: When I add something to a HashMap, is a new object copied and placed or is a reference to the original object placed?

Thanks!

Diego
  • 16,830
  • 8
  • 34
  • 46

8 Answers8

50

What's happening here is that you're placing a pointer to a list in the hashmap, not the list itself.

When you define

List<SomeType> list;

you're defining a pointer to a list, not a list itself.

When you do

map.put(somekey, list);

you're just storing a copy of the pointer, not the list.

If, somewhere else, you follow that pointer and modify the object at its end, anyone holding that pointer will still be referencing the same, modified object.

Please see http://javadude.com/articles/passbyvalue.htm for details on pass-by-value in Java.

Scott Stanchfield
  • 29,742
  • 9
  • 47
  • 65
  • 9
    Sure there is. Why do you think there's a "new" operator. Please read my article ref'd above - it'll help you understand what Java is really doing. Just because java does not implement pointers the same way C/C++ does doesn't mean it doesn't have pointers. Pascal implemented pointers without artithmetic on them... – Scott Stanchfield Jun 01 '09 at 13:45
  • 1
    Would you like to take this opportunity to make *another* link to your article? And maybe there is, but the programmer can never see them or use them in Java, so I fail to see the need to talk about them when all we use are References. – James Camfield Jun 01 '09 at 13:48
  • 4
    There can never be enough links to it... (I put it in comments to the above answers b/c they were posted first - many people won't read past the first couple answers and simply upvote them). The programmer can very well see the difference -- swap(x,y) and output/variable parameters are two very important language features that exist in some languages (C++, Ada, Pascal for example) but not in Java. – Scott Stanchfield Jun 01 '09 at 13:50
  • 1
    I'm not really clear why people are disagreeing about this. Isn't this written somewhere final? The different opinions are confusing. – Diego Jun 01 '09 at 14:57
  • It's very clear in the Java Language Specification: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.1: "When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables". – Scott Stanchfield Jun 01 '09 at 15:25
  • 2
    @Diego There are some terminology issues. If you look at the accepted terms, though, rather than what Sun "officially" calls them, it's perfectly clear what is going on. Sun defines the meanings of their names for things by using the accepted terms, in that they explicitly state that a reference *is* a pointer (JLS 4.3.1). – Adam Jaskiewicz Jun 01 '09 at 15:46
  • 3
    People see "reference" and get all confused. That Sun decided to call pointers "reference values" gets "pass-by-reference" into peoples' heads. – Adam Jaskiewicz Jun 01 '09 at 15:47
  • This is exactly why the `final` keyword is somewhat meaningless in Java. As is often the idea of immutability. – Dave Aug 15 '12 at 01:40
  • 1
    @HDave - Final affects the pointer or primitive value - it can only be set once, and is very meaningful and useful. Immutable objects, on the other hand, are completely up to the implementation. A good implementation, like java's String class, really ensures that the data held by the object cannot change. Bad implementations may leak underlying details that can be used to change the data. Good implementations are again, meaningful. – Scott Stanchfield Feb 18 '13 at 07:28
13

Java is pass-by-reference-by-value.

Adding the list to the hash map simply adds the reference to hash map, which points to the same list. Therefore, clearing the list directly will indeed clear the list you're referencing in the hashmap.

James Camfield
  • 1,636
  • 3
  • 16
  • 24
  • 7
    aaaaaaahhhhh!!! No!!!! Java is strictly pass-by-value! See http://javadude.com/articles/passbyvalue.htm – Scott Stanchfield Jun 01 '09 at 13:34
  • 2
    We know. Java is pass by value. However, saying that can be confusing. Java acts like it is pass by reference. – jjnguy Jun 01 '09 at 13:37
  • 1
    Nope - Java does not act that way at all. It acts exactly like C does (which is also pass-by-value) – Scott Stanchfield Jun 01 '09 at 13:40
  • Exactly. There no harm in seeing it as pass-by-reference, even if it does it by passing values (which is what the reference is anyway)... – James Camfield Jun 01 '09 at 13:41
  • 3
    There's a huge harm in it. Pass-by-reference semantics allow you to do things like creating a swap method (see my article that I ref in my first comment to this answer); you cannot do that in Java. – Scott Stanchfield Jun 01 '09 at 13:43
  • Well, it seems like it acts like pass by reference, because, people don't see the 'pointer' that is being passed around. It is not an easy topic to wrap ones head around. Lots of people don't know C. – jjnguy Jun 01 '09 at 13:43
  • 1
    Yep, it's not easy, which is why I wrote that article. I'm a compiler guy and a teacher; as a compiler guy, the difference is critical to implementation. As a teacher, the difference is critical to proper understanding of the language, especially why you cannot write something like swap(x,y) or have output/variable parameters. – Scott Stanchfield Jun 01 '09 at 13:48
  • I don't think it is helpful to argue about it. I like abstracting out the details and thinking about it in the bigger picture. I see where you are coming from and most definitely agree that people 'should' know how it works behind the scenes. But that doesn't mean that they have to know. – jjnguy Jun 01 '09 at 13:48
  • It's very worth arguing, because it's spreading misinformation and causing confusion with regard to how you can get data out of a method, like why if you have foo(Dog d) and write d = new Dog() inside foo, the dog pointer on the outside does not change. – Scott Stanchfield Jun 01 '09 at 13:52
  • I think pass-by-reference-by-value is actually a pretty fair representation of the true semantics. Or would you prefer pass-pointer-by-value? – Michael Myers Jun 01 '09 at 14:31
  • 1
    I wouldn't mind "pass pointer by-value" (note where the hyphen is - when you hyphenate it tends to be looked upon as official jargon). The terms "pass-by-value" and "pass-by-reference" have very specific (and important) meanings. It's really easiest to think of by separating the concepts: 1) Java has pointers 2) the value of a pointer is the target object's location 3) when you pass an arg you're passing a value 4) the target location gets passed/copied to the formal parameter. Thus you end up with the formal param pointing at the same object as the arg. – Scott Stanchfield Jun 01 '09 at 14:44
  • 4
    I don't see what's so hard to get your head around, really. It's a very distinct difference, and the only sticking point is that Sun decided to call pointers "reference values". They mention in the JLS that a reference value is a pointer to an instance or array (4.3.1), and make it pretty clear that method parameters are storing *values* (4.12.13). Thus, Java has pointers, and is pass-by-value. – Adam Jaskiewicz Jun 01 '09 at 15:30
5
Map<Integer, Integer> hasmapA = new HashMap<>();
hasmapA.put("key1", "value1");
hasmapA.put("key2", "value2");
hasmapA.put("key3", "value3");
  1. Copy By reference: If you assign one HashMap to other then both point to same reference in memory.

    Map hasmapB;

    hashmapB = hashmapA;

If you make changes in any of these, changes will reflect in both HashMap as both are referencing to same location.

  1. Copy By Value: If you wan to

clone/deepcopy/create separate memory location/create separate object

of hashmapB while copying content of hashmapA

Map<Integer, Integer> hashmapB = new HashMap<>();;

hashmapB.putAll(hashmapA)

Note: ** Have you noticed difference in both points for hashmapB declaration? In second point we have to call **HashMap constructor. So that we can putAll data of hashmapA into hashmapB.

Reference

Taimoor Changaiz
  • 10,250
  • 4
  • 49
  • 53
5

When I add something to a HashMap, is a new object copied and placed or is a reference to the original object placed?

It is always a reference to the object. If you clear the HashMap the object will be still "live". Then the object will be destroyed by the garbage collector if no one is referencing it anymore. If you need to copy it, take a look to Object.clone() method and to the Cloneable interface

daitangio
  • 583
  • 1
  • 6
  • 18
1

The Correct answer for this is Explained below : Suppose you have a HashMap called hashmap and initially you put a key value pair in this HashMap e.g. hashmap<"test1","test2">. After this when you pass this hashmap to a function where you again changes its value to test3 like hashmap.put("test1", "test3") and print the map again in main Method, the Java Pass by Value Concept fails here.

The Reason is : When you use HashMap, it does the Hashing for the Key(test1) and store the value. When you passed it to the function where it again changes its value, it again does the hashing for the same key and gets the same memory Address and changes the value Accordingly. Thats why when you try to retreive the key "test1" it gives you the result as "test3"

1

Try it out

package test32;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class Foo {
    public Foo(int id, String name) {
 this.id=id;
 this.name=name;
    }

    public static void main(String[] args) {
 HashMap strs = new HashMap();

 // create a list of objects
 List ls = new ArrayList();
 ls.add(new Foo(1, "Stavros"));
 ls.add(new Foo(2, "Makis"));
 ls.add(new Foo(3, "Teo"));
 ls.add(new Foo(4, "Jim"));

 // copy references of objects from list to hashmap
 strs.put("1", ls.get(0));
 strs.put("2", ls.get(1));
 strs.put("3", ls.get(2));
 strs.put("4", ls.get(3));

 System.out.println("list before change  : " + ls);
 System.out.println("map before change: " + strs);
 // get an object from the hashmap
 Foo f=strs.get("1");
 // set a different value
 f.setId(5);
 // observe that the differences are reflected to the list and to the hashmap also
 System.out.println("list after change  : "+ls);
 System.out.println("map after change: "+strs);
    }

    private int id;
    public void setId(int id) {
 this.id=id;
    }
    public int getId() {
 return this.id;
    }

    private String name;
    public void setName(String name) {
 this.name=name;
    }
    public String getName() {
 return this.name;
    }

    public String toString() {
 StringBuilder sb = new StringBuilder();
 sb.append(id);
 sb.append("-");
 sb.append(name);
 return sb.toString();
    }
}
stavros
  • 19
  • 1
1

Generally you always deal with references in Java (unless you explicitly create a new object yourself with "new" [1]).

Hence it is a reference and not a full object copy you have stored in the map, and changing the list will also effect what you see when going through the map.

It's a feature, not a bug :)

[1] Puritans will include "clone()" and serialization, but for most java code "new" is the way to get objects.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
-2

Geeze people...everything in Java is pass by value. When you pass an object, the value you are passing is the object reference. Specifically, you are passing a copy of the object reference. There are no pointers in Java either, though references are similar. Get it right!

GreenieMeanie
  • 3,560
  • 4
  • 34
  • 39
  • 6
    There are pointers in Java. What do you think "Dog d;" defines? If it's actually an Object, why can't you ask it to bark without pointing it: "d = new Dog();"? – Scott Stanchfield Jun 01 '09 at 13:55
  • Using the word "pointers" in Java is misleading (and NOT the correct term), giving one the impression of C-style pointers. References are not the same (and you can't manipulate references the same as "pointers"), so let us please refrain from that term in Java. – GreenieMeanie Jun 01 '09 at 14:41
  • By that logic, Pascal and Ada do not have pointers either (they both do, by the way). Not all languages allow pointer arithmetic. C/C++ were not the first languages to use pointers. You can maipulate pointers in Java the same ways you can in many langauges (assign, dereference). – Scott Stanchfield Jun 01 '09 at 14:49
  • But in Pascal and Ada, they are also called "pointers" if I recall correctly. They are not called pointers in Java. – GreenieMeanie Jun 01 '09 at 14:54
  • A rose by any other name would smell as sweet... The term "reference" in language design is similar to an alias - you're using more than one name to refer to the same variable. This is actually quite different from what Java does. Sun chose to call them references (a very poor choice, and many agree) as basically PR - they wanted to bill Java as a safe language; "no pointer arithmetic" is a big selling point, and they went overboard. "Dog d" in Java acts exactly the same as "Dog *d" in C++ (with the exception of no arithmetic) – Scott Stanchfield Jun 01 '09 at 15:06
  • 4
    @GreenieMeanie From the JLS, 4.3.1: "The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object." – Adam Jaskiewicz Jun 01 '09 at 15:07
  • 1
    One more note: NullPointerException is a really good example of how they were thinking before the PR machine started grinding. They thought of the concept as pointers, but late in the game decided to change the name and missed a spot... Note that there are language design concepts, and there are specific language designers' namings. Anyone can write a language. And unfortunately, some make naming mistakes. – Scott Stanchfield Jun 01 '09 at 15:32
  • @Adam Thanks for pointing out that quote - I hadn't noticed that before – Scott Stanchfield Jun 01 '09 at 15:36
  • 3
    -1 java does have pointers, it doesn't have pointer arithmetic. – wds Apr 28 '10 at 09:52
  • 1
    @Scott, quite agree, reference types are pointers passed by value, hence we have the NullPointerException for when the pointer is not pointed at a live object. Just because they can't be manipulated except by assignment does not mean they aren't pointers, it just means they are more tightly controlled than C/C++ etc. pointers. – Geoff Apr 28 '10 at 09:57