Vector in java

Vector is a member in Collections frame work of Java  .It implements the List interface. It is a legacy class in java.Vector was in Java in the earlier versions itself.

Vector & ArrayList

Vector is almost same as that of ArrayList.Vector also based on index values for each items. But the methods in vector class are thread safe. This gives a little performance  fall.Vector ,like ArrayList  implements the interface RandomAccess  .So the only difference between Vector and ArrayList is the thread safety of its methods.

Now let us see an example code and its output. It adds few string values to the vector .Displaying those values , then removing the strings.

import java.util.List;
import java.util.Vector;
public class VectorSample {
private List list = null;
public VectorSample() {
list = new Vector();
}
public void addItemsToList() {
String[] listItems = {"dog", "cat", "cow", "elephant", "sheep"};
for (int i = 0; i < listItems.length; i++) {
list.add(listItems[i]);
}
}
public void displayList() {
System.out.println("Displaying contents of vector");
for (String item : list) {
System.out.println("Item = " + item);
}
}
public void removeItems() {
System.out.println("Removing contents of list");
list.remove("dog");
list.remove("cat");
list.remove("cow");
list.remove("elephant");
list.remove("sheep");
System.out.println("Contents removed ,now size of vector = " + list.size());

}
public static void main(String[] args) {
VectorSample sample = new VectorSample();
sample.addItemsToList();
sample.displayList();
sample.removeItems();
}
}

Output

Displaying contents of vector

Item = dog

Item = cat

Item = cow

Item = elephant

Item = sheep

Removing contents of list

Contents removed  ,now size of vector = 0

See Related Discussions

Collections in Java

ArrayList

LinkedList

HashMap

HashSet

One thought on “Vector in java

  1. Pingback: Collections in Java | CoderPanda

Leave a Reply

Your email address will not be published. Required fields are marked *