Efficient Use of the Vector Class

Efficient Use of the Vector Class

The Vector class in java.util is one of the most frequently used classes in Java development. It almost makes the problem of memory management non-existent, unlike a fixed-size array. However, using this class doesn’t come without a cost. At instantiation, a Vector object allocates memory for 10 object references by default. This leads us to ask, “What happens when we add an 11th element to the vector?” Take a look at the following method for populating a Vector with 200 elements:

  1. public void vectorCapacity () {
  2. Vector v = new Vector();
  3. int capacity = v.capacity();
  4. int elementNo = 0;
  5. // Add 200 elements
  6. for (int i = 0; i < 200; i++) {
  7. v.addElement("FOO");
  8. // If capacity changes, print out new capacity
  9. if (capacity != v.capacity()) {
  10. capacity = v.capacity();
  11. System.out.println(i + "th element, Capacity = " +
  12. v.capacity());
  13. }
  14. }
  15. }

Calling this method produces the following output:

 10th element, Capacity = 2020th element, Capacity = 4040th element, Capacity = 8080th element, Capacity = 160160th element, Capacity = 320

When a Vector exceeds 10 objects, its capacity is increased by 10. The new capacity also defines the chunk of memory for the next aggregation. In other words, the capacity of a Vector doubles with each memory reallocation. In the example given above, the memory had to reallocate five times in order to store 200 elements.

You can avoid this problem by estimating in advance how many objects will be stored in the Vector. To increase the chunk of memory that gets allocated each time the Vector needs to increase its capacity. You can accomplish this by inserting the following between lines 3 and 4 in the code snippet above:


The output now shows:

 100th element, Capacity = 200

The number of memory reallocations is reduced to one instead of five. If you plan to use the Vector for a large number of objects, try to estimate the chunk of memory that you would want during each reallocation.

See also  10 Best Apps to Help You Read More Books in Less Time

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist