Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jun 16, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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];

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.

Duane Morse
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date