| Author |
Strange(?) behaviour
|
Stephen Pride
Ranch Hand
Joined: Sep 14, 2000
Posts: 121
|
|
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?
|
SCJP
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
Because in the second case, both Entry objects are referring to the same array object.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Greg Charles
Bartender
Joined: Oct 01, 2001
Posts: 2550
|
|
|
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.
|
 |
 |
|
|
subject: Strange(?) behaviour
|
|
|