Strange problem with class vector's addElement method
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Abhisek_Sinha
Posted On:   Thursday, July 25, 2002 08:26 AM

Hi all! There is some problem with java's vector class's addElement method. Take a look at the code import java.util.*; import java.io.*; class test { public static void main(String[] args) { String[] row = new String[2]; Vector rowVector = new Vector(); // Insert some values row[0] = "happy"; row[1] = "BirthDay"; rowVector.addElement(row); row[0] = "to"; row[1] = "you"; rowVector.addElement(row); //try this also /** * rowVector.add(rowVector.size(),row   More>>

Hi all!
There is some problem with java's vector class's addElement
method.
Take a look at the code

import java.util.*;
import java.io.*;

class test {



public static void main(String[] args) {

String[] row = new String[2];



Vector rowVector = new Vector();



// Insert some values

row[0] = "happy";

row[1] = "BirthDay";

rowVector.addElement(row);



row[0] = "to";

row[1] = "you";



rowVector.addElement(row);

//try this also

/**

* rowVector.add(rowVector.size(),row);

*/



for(int i=0;i < rowVector.size();i++) {

for(int j = 0;j < row.length;j++ ) {

System.out.println("rowVector ["+i+"]["+j+"] = " + ((String[])rowVector.elementAt(i))[j]);

}

}

/** This prints :

* row[0][0] = to

* row[0][1] = you

* row[1][0] = to

* row[1][1] = you

*/

}



}


   <<Less

Re: Strange problem with class vector's addElement method

Posted By:   Roger_Hand  
Posted On:   Friday, July 26, 2002 01:30 AM

After you've added a reference to the {"happy", "BirthDay"} array to the Vector, you change the array to be {"to","you"} and add another reference to the same array to the Vector. The vector now holds two references to the same array, which now contains {"to","you"}.


You can get what (I think) you want by putting

row = new String[2];
after adding {"happy","BirthDay"} and before setting the array to {"to","you"}. This will create a new array, so you'll have two arrays, the Vector will hold two references to the two arrays, and you'll get all four words output.
About | Sitemap | Contact