Forums Register Login

Confusion about copying in Java

+Pie Number of slices to send: Send
Hi there,
I have been programming in C++ for the last while and am once again using Java. I don't have a lot of experience in Java in the first place so there's a few things that aren't coming back to me right away.

What I am unsure about at the moment is Java's automatic copying of objects.

DocIDFrequencyList is essentially a HashMap.
Is there any difference between the following code snippets?
A:


B:


Thank you for any help.
+Pie Number of slices to send: Send
There is a difference between the two snippets:

In B: you simply copy the reference to the DocIDFrequencyList from one Map to another. If you were to change the List in the first Map (for example delete one of the values) then the same change would be seen in the second Map, because both maps point to the same DocIDFrequencyList.

In A: you make a new DocIDFrequencyList and copy the contents from the old DocIDFrequencyList into the new one. If you modify the DocIDFrequencyList in the first Map then the second Map would not see that change.
+Pie Number of slices to send: Send
 

Kirsty Beaton wrote:
What I am unsure about at the moment is Java's automatic copying of objects.



There isn't any. Copying an object only occurs when you explicitly ask it to, such is via the clone() method or a "copy constructor" (put into quotes because, while functionally similar to the same concept in C++, it's not part of the language, just a c'tor form that is added to some clsases).
+Pie Number of slices to send: Send
If you are used to C++, there is one important difference between Java and C++ to be aware of: in Java, variables (of non-primitive types) are not the objects themselves like in C++, they are references to objects.

When you assign the value of one (non-primitive) variable to another, you are not copying the object. You're only copying the reference to the object, and you'll end up with two variables that refer to the same object; not two separate objects.
+Pie Number of slices to send: Send
 

Jesper de Jong wrote:If you are used to C++, there is one important difference between Java and C++ to be aware of: in Java, variables (of non-primitive types) are not the objects themselves like in C++, they are references to objects.



And a reference in Java is much more like a C++ pointer than like a C++ reference.



+Pie Number of slices to send: Send
Thank you all for your helpful responses.

Java's starting to come back to me now.
You can't have everything. Where would you put it?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 635 times.
Similar Threads
HashMap's Map.Entry interface
ListOrderedMap
Difficulty Using checkboxes in JSF
ClasscastException in Collections.sort()
Generics Question: Map and Map.Entry
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:36:53.