View RSS Feed

My Java Tips

Using Vectors in Java

Rate this Entry
by , 11-10-2011 at 06:03 PM (1383 Views)
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:

Java Code:
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:

Java Code:
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.

Java Code:
Vector  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.

Submit "Using Vectors in Java" to Facebook Submit "Using Vectors in Java" to Digg Submit "Using Vectors in Java" to del.icio.us Submit "Using Vectors in Java" to StumbleUpon Submit "Using Vectors in Java" to Google

Categories
Java SE

Comments