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.


Share the Post: