Re: Strange behavior of a java.util.Vector
From: chris (chris_at_kiffer.eunet.be)
Date: 01/25/04
- Next message: Konrad Den Ende: "Re: Strange behavior of a java.util.Vector"
- Previous message: Jan van Mansum: "Re: Strange behavior of a java.util.Vector"
- In reply to: Konrad Den Ende: "Strange behavior of a java.util.Vector"
- Next in thread: Konrad Den Ende: "Re: Strange behavior of a java.util.Vector"
- Reply: Konrad Den Ende: "Re: Strange behavior of a java.util.Vector"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 25 Jan 2004 23:28:03 +0100
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];
Note that there is only one array outPutLine, and its value never changes:
it always refers to the same array of 3 String's.
> 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:");
Let's unwrap the outer loop.
int k = 0;
for (int i = 0; i < outPutLine.length; i++)
outPutLine[i] = "S(" + i + ";" + k + ")";
vec.add (outPutLine);
// [...]
}
k = 1;
for (int i = 0; i < outPutLine.length; i++)
outPutLine[i] = "S(" + i + ";" + k + ")";
// Note that we are overwiting the elements of outPutLine from the previous
iteration
vec.add (outPutLine);
// Note also that we add the same object outPutLine to the Vector eac time
// (so at the end we will have a Vector of four references to the same
object)
// [...]
}
k = 2;
// [etc...]
> So, is it just me or is there funky with the output? Where did the
> element S(0;0) go, for instance?!
You overwrote it with S(0;1).
Suggestion: move the assignment "outPutLine = new String[3];" inside the
"for (int k ...)" loop. That way you will be creating four String[3]'s,
which is useful if you want to store 12 separate strings ...
Mut,
Chris
-- Chris Gray chris@kiffer.eunet.be /k/ Embedded Java Solutions
- Next message: Konrad Den Ende: "Re: Strange behavior of a java.util.Vector"
- Previous message: Jan van Mansum: "Re: Strange behavior of a java.util.Vector"
- In reply to: Konrad Den Ende: "Strange behavior of a java.util.Vector"
- Next in thread: Konrad Den Ende: "Re: Strange behavior of a java.util.Vector"
- Reply: Konrad Den Ende: "Re: Strange behavior of a java.util.Vector"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]