1

I hope I am just confused now because my Java program behaves strange.

I have the following code:

Iterator<Entry<DateTime, Double>> itCur = this.curIntervalValues.entrySet().iterator();

Entry<DateTime, Double> last = null;
while (itCur.hasNext()){
  Entry<DateTime, Double> curr =  itCur.next();
  //more code between
  last = curr;
}

My question is quite simple: does last = curr; makes a deep copy of curr? Or does last now every time changes if curr changes?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
cruxi
  • 819
  • 12
  • 28

2 Answers2

4

When executing last = curr, last won't be a copy of the current item, it will be the current item reference. So if you edit its fields, you will edit the fields of the curr object reference as well. For example, if you execute

System.out.println(last.getSomeProperty());
last.setSomeProperty(newValue);
System.out.println(last.getSomeProperty());

It will print

oldValue
newValue

And your reference will be modified in your collection as well.

does last now every time changes if curr changes?

Short answer: yes.


By your comment, looks like you want a clone of the data handled by curr. If so, I would recommend following one of the approaches stated here: Java: recommended solution for deep cloning/copying an instance

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

Entry<DateTime, Double> is an object, therefore it is stored by reference, meaning that only the object's location in memory is stored in the variable. So yes, if you do last = curr, last will change if you alter curr.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85