Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange(?) behaviour

 
Stephen Pride
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a small program that reads in integer values from a comma-dilimited file. What's strange is that depending where I place a local integer array, the output changes. Here is the code ...

Now, if I uncomment the line that says "// BAD" and comment the line that says "// GOOD", the data stored in the Vector is always the same for each element.
IOW, if the first line read is "1,2,3,4,5" and the second line read is "6,7,8,9,0", executing the original code will produce a Vector with two Element objects: the first (0-index) Element object will have the integer data {1,2,3,4,5} and the second (1-index) Element object will have the integer data {6,7,8,9,0}. However, if I change the code as described in the previous paragraph, the first Element object will have the integer data {6,7,8,9,0} and the second Element object will have the integer data {6,7,8,9,0}.
Anyone know why?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because in the second case, both Entry objects are referring to the same array object.
 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, Ilja is right. What you probably want to do during the Entry constructor, since you've already created an array in Entry, is just copy the values from the parameter "d". Actually, it's probably better to wait and create the array in the constructor, since you don't know the passed array will always have size 5. Take a look at System.arraycopy() in the Java Docs.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic