Saturday, 15 February 2014

Java: Vector Example

A Java Vector is similar in many aspects to an ArrayList but it is synchronized. A Vector implements a dynamic array.

Here is an example demonstrating the vector operations:

  • How to initialize a vector
  • How to populate a vector adding one element at a time
  • How to add multiple elements to a vector atonce
  • How to add a Collection - List to a vector
  • How to add an array to a vector
  • How to display / read data from vector using for() loop
  • How to display / read data from vector using Enumiration
  • How to display / read data from vector using Iterator

public class VectorExample
{
private Vector<String> stringVector = new Vector<String>(10, 2);

// Initial size of the vector is 10 and when more then 10
// elements will be added then the size will increase by 2.

public VectorExample()
{
populateVector();
addListToVector();
addArrayToVector();
displayData();
readVectorUsingEnumeration();
readVectorUsingIterator();
}

private void populateVector()
{
String str = "Index";

for (int i = 0; i < 10; i++)
{
stringVector.addElement(str + i);
}
}

private void displayData()
{
for (String s : stringVector)
{
System.out.println(s);
}
}

/*
* This shows how to add an entire list to a vector
*/
private void addListToVector()
{
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
stringVector.addAll(list);
String[] array =
{ "array1", "array2", "array3" };
stringVector.addAll(Arrays.asList(array));
}

/*
* Adding a string array to a vector
*/
private void addArrayToVector()
{
String[] array =
{ "array1", "array2", "array3" };
stringVector.addAll(Arrays.asList(array));
}

/*
* Reading a vector data using Enumeration
*/
private void readVectorUsingEnumeration()
{
Enumeration<String> enm = stringVector.elements();
while (enm.hasMoreElements())
{
System.out.println(enm.nextElement());
}
}

/*
* Reading a vector data using Iterator
*/
private void readVectorUsingIterator()
{
Iterator<String> itr = stringVector.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
}
}

No comments:

Post a Comment