hi! can u pl explain the output of this code? thanx. ashok. _______________ import java.util.*; class Tom { public static void main(String args[]) { Vector v = new Vector(1); System.out.println(v.capacity()); v.add("ashok"); v.add("vikas"); v.add("john"); System.out.println(v.capacity()); } }

Vectors add method Appends the specified element to the end of this Vector. In your program you created a vector with capacity 1 but you added 3 later on..so that makes it 4. That the reason for the 2nd system out to print 4. Correct me if I am wrong. Roopa.

Originally posted by ashok khetan: hi! can u pl explain the output of this code? thanx. ashok. _______________ import java.util.*; class Tom { public static void main(String args[]) { Vector v = new Vector(1); System.out.println(v.capacity()); v.add("ashok"); v.add("vikas"); v.add("john"); System.out.println(v.capacity()); } }

If you change creation of the new Vector to: new Vector() the println will be 10 and 10. The question is testing your knowledge of capacity and size methods and what they return. The initial capacity of Vector is 10 if not otherwise stated. The size is the number of elements in the Vector.

Hi Ashok, It also shows that the Vector capacity increment is 1 unless otherwise specified. For example, we could have the following: Vector v = new Vector( 1, 5 ); in the original code shown. Then the second println would have printed 6. Once we got past 1, the capacity would have grown by 5 elements. Regards, Manfred.

when using add() and there is no room in the Vector, then the capacity will be increased. the rule is: 1. if the Vector is created by no parameter (e.g. Vector v = new Vector()) then the capacity will be doubled based on 10. that is 2*10, 2*2*10, 2*2*2*10, .... (2^i * 10) 2. if the Vector is created by one parameter (e.g. Vector v = new Vector(n)) then the capacity will be doubled based on n. that is 2*n, 2*2*n, 2*2*2*n, .... (2^i * n) for n = 1, it will be 2,4,8,18... for n = 2, it will be 4,8,16,32... for n = 3, it will be 6,12,24,48... ... 3. if the Vector is created by two parameter (e.g. Vector v = new Vector(l, m)) then the capacity will be increased by the size. that is 2*(m-l+1), 3*(m-l+1), 4*(m-l+1) .... (i*(m-l+1)) for n = 1, it will be 1,2,3,4... for n = 2, it will be 2,4,6,8... for n = 3, it will be 3,6,9,12... ...