Using Vectors in Java

4 November 2007

Vectors are very useful to store objects for later use. One may define vector as a growable array of objects, so no need to specify the size of Vector while declaring it.

Vector stores objects which can even be an object of user made class. For example: we want to store 2 string objects in a vector. Then we want to store an object of user made class TestClass also in the same vector. This is possible.

Vectors belong to java.util package so import it before using. While declaring Vector, you may specifiy the size of Vector. But usually the Vector constructor without arguments is preferred.

TestClass is as below:

public class TestClass {
 
	private int age;
	private String Name;
 
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
 
}

Storing string and TestClass objects in the same vector:

Vector v = new Vector();
v.addElement("Australia");
v.addElement("Brazil");
 
TestClass obj = new TestClass();
 
obj.setName("Dave");
obj.setAge(22);
 
v.addElement(obj);

However, there are situations when you don’t want to practice this freedom given by vector and want to store only one type of objects in a vector. This is useful for better control specially when a project is being developed in a team and you want you team mates to store only a particular type of object in a vector you declared.

Vector <String> v = new  Vector();
v.addElement("Australia");
v.addElement("Brazil");
 
TestClass obj = new TestClass();
 
obj.setName("Dave");
obj.setAge(22);

In the example above, Vector is of type String and will only store objects of type String. If you try to save an object of class TestClass, you will get syntax error saying:

The method addElement(String) in the type Vector is not applicable for the arguments (TestClass)

So it depends on you what you want to do.

del.icio.us:Using Vectors in Java  digg:Using Vectors in Java  spurl:Using Vectors in Java  wists:Using Vectors in Java  simpy:Using Vectors in Java  newsvine:Using Vectors in Java  blinklist:Using Vectors in Java  furl:Using Vectors in Java  reddit:Using Vectors in Java  fark:Using Vectors in Java  blogmarks:Using Vectors in Java  Y!:Using Vectors in Java  smarking:Using Vectors in Java  magnolia:Using Vectors in Java  segnalo:Using Vectors in Java  gifttagging:Using Vectors in Java

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Using Vectors in Java

One Response to “Using Vectors in Java”

  1. Programmer Says:

    ArrayList is the preferred alternative (it has the advantage of being unsynchronized, which is preferable for most uses). Also, your advice makes no mention of generics, which have been a key part of using collections in Java for at least 3 years.

Leave a Reply