Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
67 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:

Contents
 Arrays
 Vectors
 OOP
 Files
 Arrays in Games

 Printable version
 Discuss this article
 in the forums


The Series
 The Basics
 Making a
 Simple Game

 The Power of Arrays

Vectors

Now that we have taken a look at how to work with arrays in Java it is important to take a look at a useful data structure that is also available to us, the Vector. The Vector is fancy array that Java allows us to use. This fancy array dynamically alters its size to fit the data that we store in it and also makes access to the elements within extremely easy. This means that we can keep track of a number of elements without knowing in advance how many there will be.

Useful Vector methods are:

  • addElement()
  • elementAt()
  • firstElement()
  • lastElement()
  • isEmpty()
  • size()

To initially create a Vector we declare our variable as normal and then set that variable equal to a new Vector.

Vector sample = new Vector(0,1);

The first parameter in the constructor for the new Vector is the initial capacity that we want it to have. The second parameter is the number of new elements that will be added to our Vector when we run out of elements that we can store information in. If you think that you will be adding a large number of elements to your Vector you may wish to have larger values for the intial capacity and the capacity increase. A problem that we have to watch out for here is that we don’t end up wasting space (ie. having empty elements sitting around).

When new elements are added via the addElement method they are added to the end of the Vector.

int number = 5;
sample.addElement(number);

In order to get elements out of the Vector we use the elementAt method and pass to it the index of the element that we wish to access. Another useful method that can be used in conjunction with the elementAt method is the size method. The size method allows us to find out the number of elements that we have in our Vector and the value passed back from this method could be used as an upper limit in a for loop.

int number2 = (int)sample.elementAt(1);

The methods firstElement and lastElement are similar to elementAt, but they return either the first or last element and are not passed an index value.

While you may not immediately find a use for the Vector in your games it is a powerful tool that is available to you to use. I am sure that you will find a point where a Vector will fill an important position in one of your games and make your life easier.





Next : Object-Oriented Programming