I am trying to create a two-dimensional data structure using vectors. My plan has been to add two elements to an 'inner' vector, then add this vector to an 'outer' vector.
The problem I am having is: accessing the inner vector once it's been placed in the outer one.
Can anyone see where I am going wrong in this test method ?
Thanks in advance.
private void test( ) {
Vector inner=new Vector( );
Vector outer=new Vector( );
String st1="1";
String st2="2";
String f="";
inner.addElement(st1);
inner.addElement(st2);
outer.addElement(inner);
inner.removeAllElements( );
for (Enumeration e=outer.elements( );e.hasMoreElements( );) {
Object i;
i=e.nextElement( );
try {
inner=(Vector) i.clone( );
}
catch (CloneNotSupportedException ex) {
}
f = f + (inner.elementAt(0)) + " " + (inner.elementAt(1)) +"\n";
inner.removeAllElements( );
}
results.setText(f);
}
('results' is a TextArea defined elsewhere in the code)
Michael Clark
michael.p.clark@student.shu.ac.uk
basically you should replace your line
"inner.removeAllElements( )"
with
"inner = new Vector( )
When you assign a value to a new variable, it doesn't give the actual value to the new variable , it gives the memory reference pointer.
So, let's say we have
Vector inner = new Vector( );
Vector outer = new Vector( );
that reserves a space for a vector out in computer memory space and gives the location of that reserved space to inner the same goes for "outer"
Now say you do this:
inner.addElement("A");
a letter "A" is created out in the vast memory space and the location of the letter is given to inner[0]
next up would be:
outer.addElement(inner)
now, applying the same logic as before, we see that "outer" doesn't actually get it's own "A" like "inner" did ... it gets whatever "inner" is, even if "inner" changes later...this is what is known as a shallow copy and is the source of many errors (and also a problem when using clone which I see you've implemented as well, so be careful). You can test this by changing "outer" and watch "inner" change as well.
Anyways, next you tried to recycle "inner" by using:
inner.removeAllElements( );
this not only changed "inner", but it changed "outer" as well, because "inner" and "outer" still point to the same memory space (which you've now erased all values from)
The easiest solution is to do this:
inner = new Vector( )
this leaves "outer" alone by changing the memory space address "inner" contained
Another solution which you may have to implement (especially when using the "clone" method) is to perform the creation of a deep copy, as opposed to a shallow copy
so, instead of this:
inner.addElement("A");
outer.addElement(inner);
you could have done this:
inner.addElement("A");
Vector vecTemp = new Vector( );
String strTemp;
for (i = 0; i{
strTemp = inner.elementAt(i);
vecTemp.addElement(strTemp);
}
outer.addElement(vecTemp);
now outer is a deep copy of inner, which means you can change either and only change that one variable
Mike
mdsgt@yahoo.com