devxlogo

Vector vs. Array–the Best of Both Worlds

Vector vs. Array–the Best of Both Worlds

It’s often pointed out that the Vector class is expensive to use because all of the methods are synchronized. Java 2 has the LinkedList class, which can serve the same purpose without the performance penalty. In the meantime, however, there’s a simple approach you can take to one common use of Vectors that largely avoids the performance problem.

Often you use a Vector during the configuration stage of an application to create and hold objects of some sort because there’s no way to tell ahead of time how many objects will be needed. At the end of configuration, however, the list won’t change. The compromise is to use a Vector to build the list, and then turn the list into an array. For instance, suppose vec is the name of the Vector, and it holds objects of type MyObject:

   int nSize = vec.size();  MyObject aobj = new MyObject[nSize];  vec.copyInto(aobj);

The copyInto() method copies the Vector elements into the specified array.Thereafter, you can use the array as a much faster container for those objects, and you can discard the Vector.

devxblackblue

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