• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strange(?) behaviour

 
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because in the second case, both Entry objects are referring to the same array object.
 
Sheriff
Posts: 3063
12
Mac IntelliJ IDE Python VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic