File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Strange(?) behaviour Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strange(?) behaviour" Watch "Strange(?) behaviour" New topic

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?

Ilja Preuss

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

Joined: Oct 01, 2001
Posts: 2968

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.
I agree. Here's the link:
subject: Strange(?) behaviour
It's not a secret anymore!