InterviewSolution
| 1. |
How to differentiate between the size and capacity of a Vector in Java? |
|
Answer» Vectors in Java are dynamic data structures which can expand when a new element is added to them. They are synchronized and contain many methods that are not a PART of the Collections framework in Java. Vectors in Java have two methods call size() and capacity() which are in relation with the NUMBER of elements of the Vector. The size() returns the number of elements the vector is CURRENTLY holding. It increases or decreases whenever elements are inserted or deleted to/from a vector respectively. The capacity() returns the maximum number a elements a vector can hold. Since the vector is an expandable data STRUCTURE, its capacity is not fixed. We can set the initial value of the capacity. The Vector() constructor initializes the initial capacity of the vector to be 10. For example, import java.util.*; // Vector is a class of the java.util package public class Example { public static void main (String[] args) { Vector v = new Vector(); // creating new Vector object System.out.println("Vector Size: " + v.size()); // prints the current size of the Vector v.addElement(10); v.addElement(20); System.out.println("Vector Size: " + v.size()); v.addElement(5); System.out.println("Vector Size: " + v.size()); System.out.println("Vector Capacity: " + v.capacity()); //prints the capacity of the vector } }The output will be the following: $javac Example.java $java Example Vector Size: 0 Vector Size: 2 Vector Size: 3 Vector Capacity: 10 |
|