Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Tutorial] Java Vectors
Index -> Programming, Java -> Java Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Hikaru79




PostPosted: Wed Dec 22, 2004 1:40 am   Post subject: [Tutorial] Java Vectors

If you come from the good ol' days of Turing, you're probably familiar with the idea of a 'flexible array.' A collection of items whose capacity to store information can be increased and decreased at whim. Upon arriving at Java, you'll quickly realize that Java's "Array" object has no such feature. Worry not, though! Java has an alternative, one which is easy to use and has all the features you could want. I introduce to you, Java hopefuls, the Vector.

Importing
This is easy. Vectors are a part of the java.util package. Therefore, all you need to add Vectors to your program is:
Java:
import java.util.Vector;


Creating a New Vector

The Vector has a few constructor methods. I'll go over the more complex one over with you, and it really should be the only one you ever use.

Java:
public Vector (int initialCapacity, int incr) {


The first arg, initialCapacity, sets the original size of the Vector. The second arg, incr, means increment -- how much will be added to the capacity every time it needs to be expanded. For example
Java:
Vector v;
v = new Vector (5,3);

This will create a new Vector that has a size of 5 -- it can store 5 pieces of information. If you try to store a sixth piece, it will automatically jump to 8 (5+3). If you add nine, it'll jump to 12, and so on. How does one add to a Vector, you ask?

Adding to a Vector

There are actually three ways to do this, all of them very simple. This should be a breeze for someone as smart as you, right? Smile

First of all, the easiest way to add to a vector is
Java:
public boolean add (Object o) {

This will simply take your Object (such as a String, Integer, Float, or just about anything else) and append it to the next slot in the Vector. If the Vector is at its full capacity, it will expand the Vector by whatever amount you set in the constructor method. If you used one of the other constructor methods that did not require an increment, it will double whatever capacity it had before. The return type of this method is 'boolean' but it will always return true as long as the operation was carried out succesfully.

Of course, sometimes you'll want to stick an object into a Vector in some place besides the very end of it. So we have:
Java:
public void add (int index, Object o){

This looks a lot like the other add, except now we're telling it where in the array to place the Object (that's what the first argument is). If the index already has something in it, then add will shift all of the elements following this array down (by adding 1 to their indices). So, for example:
Java:
v.add(5,"Five");

will add the string "Five" to the fifth position in the vector. The previous fifth element will become the sixth element, the previous sixth will become the seventh, and so on. Careful, though-- this method can throw an ArrayIndexOutOfBoundsException if the index is not valid.

The last main way of adding to a Vector is by replacing a specific index with some other data without affecting any of the indices after it.
Java:
public void setElementAt(Object o, int index) {


This should be pretty obvious. setElementAt will replace whatever was at index 'index' with 'o' and leave the rest of the Vector untouched. So, continuing our previous example,
Java:
v.setElementAt("Six",5);

will replace the "Five" object we just added in the last step to "Six."

Removing Elements in a Vector

Removing elements in an array works a lot like adding them.

Java:
public Object remove(int index){

This will remove whatever object was at 'index' from the Vector, and shifts all the indices after it back one position (subtracts 1 from their position). It returns the Object that was removed. The complement to this method is:

Java:
public int remove(Object o){

This method, very useful, will look through a vector for the first occurence of Object o, remove it, shift all the remaining indices down one, and return the position that was removed. And finally,

Java:
protected void removeRange(int lowerBound, int upperBound){

This method will remove an entire range of indices. For example, if you have a Vector of 10 indices, and the objects contained is a String containing the word that represents it's index (5 = "Five", etc) then
Java:
foo.removeRange(3,6);

will leave you with a vector that looks like ("One","Two","Six","Seven","Eight","Nine","Ten"). The lower bound is inclusive, the upper bound is EXclusive.

To Be Continued...
Well, there's lots more to Vectors than this, of course Smile But first I want to get some feedback on what I have so far, and see if anyone's interested in the rest of this. Coming up next: How to have your vectors interact with Collections and Arrays directly! Also, some important vector diagnostic tools (finding it's current size, capacity, etc).

See you next time! Very Happy
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Wed Dec 22, 2004 12:16 pm   Post subject: (No subject)

very nice have some bits.

+10 bits
Tony




PostPosted: Wed Dec 22, 2004 10:46 pm   Post subject: (No subject)

that's awesome +50Bits

also, wtd explains the advantage of Vectors over Arrays. Check that out.
wtd




PostPosted: Wed Dec 22, 2004 11:42 pm   Post subject: (No subject)

tony wrote:
that's awesome +50Bits

also, wtd explains the advantage of Vectors over Arrays. Check that out.


It should be noted that there are singificant differences between C++ vectors and Java's collection class by the same name.

Additionally, there are significant differences between Java 1.4.2 and Java 5.0 on this particular issue.
Andy




PostPosted: Mon Apr 25, 2005 7:49 pm   Post subject: (No subject)

i've recently picked up java and im noticing that its drastically different from the vectors in c++.. quck question, if i were to add an object to a vector, then later change one of the member variables inside the object, will the value stored in the vector change too?
wtd




PostPosted: Mon Apr 25, 2005 8:04 pm   Post subject: (No subject)

Andy wrote:
i've recently picked up java and im noticing that its drastically different from the vectors in c++.. quck question, if i were to add an object to a vector, then later change one of the member variables inside the object, will the value stored in the vector change too?


Java's Vector class only holds objects, and objects are always by reference rather than value in Java.

C++'s std::vector class holds values by default.

So, yes.
Andy




PostPosted: Tue Apr 26, 2005 7:44 pm   Post subject: (No subject)

and the same for hashtable and hashmaps too rite?
1of42




PostPosted: Tue Apr 26, 2005 10:01 pm   Post subject: (No subject)

I find Vectors in Java to be annoying, and generally unproductive, except in the very certain circumstances when you legitimately do not know the length of the dataset you're getting, or certain other narrow cases.

In C++, I almost exclusievly use vectors Very Happy
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Tue Apr 26, 2005 10:07 pm   Post subject: (No subject)

uhuh.... can YOU give me an example as to how java Vectors are unproductive? or annoying for that matter...
Hikaru79




PostPosted: Wed Apr 27, 2005 12:06 am   Post subject: (No subject)

Andy wrote:
and the same for hashtable and hashmaps too rite?

Yes. In Java, all objects are passed as references only. Only primitive types, afaik, send an actual value. So in any method, etc, a change to an object in that method is global. Java collections (hashtables, etc), are no different.
HyperFlexed




PostPosted: Tue Nov 08, 2005 6:25 pm   Post subject: (No subject)

Vectors have been driving me insane... I have a question. Do vectors utililize the Zeroeth element like arrays?

I must thank you though, Hikaru. I am writing a program that parses a made-up language in my course, and I have been storing the commands in a Vector, and I keep getting errors. Another question, how do I set the size of a vector manually, setSize (int)?
Display posts from previous:   
   Index -> Programming, Java -> Java Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 11 Posts ]
Jump to:   


Style:  
Search: