1. Home
  2. Computing & Technology
  3. Focus on Java

Java Vectors and Java Arrays

What's the Difference?

From Earline Gilley, for About.com

The Vector

Vectors and Arrays in Java are objects that allow you to store multiple similar items in one convenient place. Let’s say that you would like to create a Java program that lets users create a grocery shopping list. To store those items in the shopping list, you would use a Vector object.

You may be wondering “Why should I use a Vector and not an Array for my shopping list?”

Since you do not know how many items are going to be in the shopping list (maybe the user needs milk and bananas today, but tomorrow needs coffee, juice, and sugar) then you will want to use the dynamic Vector object. Vectors, unlike Arrays, can grow and shrink during their lifecycle. You can add elements to a Vector whenever you need to. So the convenience of using a Vector is its ability to change size, but there is a drawback. Vectors are a little slower than their counterpart, the Array.

The Array

An Array would not be such a good choice for the shopping list program because we do not know how many items the user is going to want on their shopping list. But if we were creating a different program, such as an animal health application for a zoo, then we could find a perfect use for the Array.

import java.util.Arrays;

public class AnArrayExample {

   public static void main(String[] args) {
     String animalsArray[];
     animalsArray =new String[8];

     animalsArray[0] = "Aves";
     animalsArray[1] = "Mammalia";
     animalsArray[2] = "Reptilia";
     animalsArray[3]= "Osteichthyes";//fish
     animalsArray[4]= "Amphibia";
     animalsArray[5] ="Chondrichthyes";
     animalsArray[6] = "Placodermi";
     animalsArray[7]="Agnatha";
    System.out.println("The animal phylum at index 2 is "+ animalsArray[2]);
   }

 }

The code above spits out:
The animal phylum at index 2 is Reptilia.

We know that there are 8 phylums in the Animal Kingdom. This figure is unlikely to change, so we may choose to store our animal phylums in an Array object. We can set the size of the Array ahead of time ( I set the size to 8 in the code above), thereby allocating the right amount of memory for the Array.

One more thing to note is the indices of the array. I set my array to be a size 8, but I started my index at animalsArray[0] and ended at animalsArray[7]. Don't let this fool you. There are still 8 slots available to hold my animal phylums. Just remember that in Java array indexes start at 0.

So, Vectors are great for collections of similar items when you don’t know how many items there will be. Arrays are best suited for collections with a predetermined and fixed size.

Explore Focus on Java

More from About.com

  1. Home
  2. Computing & Technology
  3. Focus on Java
  4. Java from Scratch
  5. Java Vectors vs Java Arrays

©2008 About.com, a part of The New York Times Company.

All rights reserved.