Vector problem

A

anshul

Hi I wish to add object in a list of vectors
But when I add the same object to the vector list, it is overwritten to
that list, instead of being appended.
Here is my code :

String r;
ResultWrapper rw = new ResultWrapper();
ResultWrapper rw1 = new ResultWrapper();
Vector <ResultWrapper> vec = new Vector <ResultWrapper>();
rw.setJobName("Job1");
rw.setJobId("IDJob1");
vec.addElement(rw);
rw.setJobId("IDJob2");
rw.setJobName("Job2");
vec.addElement(rw);

ListIterator iter = vec.listIterator();
while(iter.hasNext())
{
rw1 = (ResultWrapper) iter.next();
r = rw1.getJobName();
System.out.println("Job name is " + r);
r = rw1.getJobId();
System.out.println("Job Id is " + r);

} // end of while iter.next()



Here is the output of my code :

Job name is Job2
Job Id is IDJob2
Job name is Job2
Job Id is IDJob2


How to get this output?
Job name is Job1
Job Id is IDJob1
Job name is Job2
Job Id is IDJob2
 
C

Chrisie

Your problem is in the lines:
rw.setJobId("IDJob2");
rw.setJobName("Job2");
What you are doing here is changing the values of the JobName and JobId
stored in the object to which you are using rw as a reference. This
results in changing the values of the object you have already in the
Vector, and then with the line
vec.addElement(rw);
you add it in the vector again and this is why when you are printing
the vector you get the same thing twice.
What you should do to avoid this is create a new ResultWrapper object
after adding the first one in the vector and then give it the values
you want like this:
rw.setJobName("Job1");
rw.setJobId("IDJob1");
vec.addElement(rw);
rw=new ResultWrapper();
rw.setJobId("IDJob2");
rw.setJobName("Job2");
vec.addElement(rw);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top