Re: Strange behavior of a java.util.Vector

From: Jan van Mansum (jvm_at_nospam.com)
Date: 01/25/04


Date: Sun, 25 Jan 2004 23:11:33 +0100

Remember that in Java all objects and arrays are actually references
(like pointers). So you are adding the same "reference to an array"
(namely the array "outPutLine") three times. All three elements of the
Vector will point to the same array.

HTH, regards,
Jan van Mansum.

Konrad Den Ende wrote:

> I'm not sure if i'm going mad or stupid but as far as i can rely
> on my eyes, when i ADD an element to a Vector, it gets put on
> ALL the position, instead of the last one. It's like if it rolls all
> the way down the list leaving its footprints along the way.
>
> I wrote, like:
> import java.util.*;
>
> public class Temp {
> public static void main (String[] arg) {
> Vector vec = new Vector ();
> String[] outPutLine = new String[3];
> String line;
> for (int k = 0; k < 4; k++) {
> for (int i = 0; i < outPutLine.length; i++)
> outPutLine[i] = "S(" + i + ";" + k + ")";
> vec.add (outPutLine);
>
> System.out.println ("outPutLine " + k + " is: \t\t" + outPutLine[0] +
> "\t" + outPutLine[1] + "\t" + outPutLine[2]);
> System.out.println ("The result is:");
>
> String test = "";
> for (int i = 0; i < vec.size (); i++) {
> for (int j = 0; j < 3; j++)
> test += ((String[])vec.get (i))[j];
> test += "\n";
> }
> System.out.println (test + "\n---------------------------------\n");
> }
> }
> }
>
> So, is it just me or is there funky with the output? Where did the
> element S(0;0) go, for instance?!
>



Relevant Pages

  • Re: list implementation
    ... >I believe the type "list" is implemented as an array of pointers. ... A Python list is sematically/behaviorally defined as a mutable extensible ... the references are arrays of C pointers. ...
    (comp.lang.python)
  • Re: CFO: Why C?
    ... Renaming pointers to ... >>references doesn't change anything fundamental. ... integer from a byte array is another example. ... Even if I did, the compiler would ...
    (comp.os.linux.development.apps)
  • Re: CFO: Why C?
    ... The difference between pointers and references is more than only a rename. ... Consider a loop over ... an array, where in traditional code often a pointer as well as an index (loop ...
    (comp.os.linux.development.apps)
  • Re: Template collection classes
    ... Not references to CPoint's or pointers to CPoint's. ... CArray< CPoint, CPoint &> ... I am not sure it is legal with a CObList, but CTypePtrArray is used typically with an array of pointers. ... You can store an array of "things" or an array of "pointers to things". ...
    (microsoft.public.vc.mfc)
  • Re: changing the value in an Array with C
    ... >> some things I just can't get my head around, notably pointers, references ... >> and passing arrays. ... I have tried various tutorials and online references, ... > third or Nth - object in an array of objects). ...
    (alt.comp.lang.learn.c-cpp)