class A{
Vector<String> s = new Vector<String>();
}

public class Vec {

public static void main(String[] args) {

    A a = new A();

    a.s.add("String1");
    a.s.add("String2");
    a.s.add("String3");
    a.s.add("String4");
    a.s.add("String5");
    Vector<A> vecA = new Vector<A>();
    vecA.add(a);

    System.out.println("Size of vector is "+vecA.size());       // here i am getting size one

    a.s.clear();

    a.s.add("String6");
    a.s.add("String7");
    a.s.add("String8");
    a.s.add("String9");
    a.s.add("String10");
    vecA.add(a);

 System.out.println("Size of vector is "+vecA.size()); // here i am getting size 2


 for(int i=0;i<vecA.size();i++)
 {
  System.out.println(vecA.get(i).s.get(0));
  System.out.println(vecA.get(i).s.get(1));
  System.out.println(vecA.get(i).s.get(2));
  System.out.println(vecA.get(i).s.get(3));
  System.out.println(vecA.get(i).s.get(4));
 }


  }
}

 output :
size of vector is 1
 size of vector is 2

String6
String7
  String8
String9
String10
String6
String7
String8
String9
String10


Here i am facing problem.

in vecA at index-0 i stored String1,String2,String3,String4,String5
 and    at index-1 i stored String6,String7,String8,String9,String10

 but in output at index-0 and index-1 i am getting same output as in index-1.

 please tell me where the fault is ?

 Thank,
 pavan.

your fault is that you store a reference to the vector in the other vector. since you overwrite the values in that subvector, it changes in the result as well.

at line no. 17 i am pushing data to vecA at index 0.
at line no. 28 i am appending data to vecA (it will be stored at 1st index.

Still i am unable to find the problem.please show me sample code to these type of vectors.

Thanks,
pavan.

User defined types will pass their pointers, not their contents, when appended to vectors. The memory address of a is stored at the first slot of the vector. Because the A in the vector points to the same memory location as a, the contents of the one in the vector also changes once you execute lines 23 to 27. To prevent the change, make a a new instance of class A before changing the values.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.