How to add elements of another collection in vector in java.

How to add elements of another collection in vector in java.


Posted in : Core Java Posted on : December 11, 2010 at 6:07 PM Comments : [ 0 ]

How to add elements of another collection in vector in java.

How to add elements of another collection in vector in java.

In this example, you will see how to add elements of another collection into vector. For this, we require another collection object; which we wants to add in vector. So here, we are using a ArrayList class. The Vector class provides different constructor for creation of vector object. The Vector(collection c) is also a constructor of java Vector class. It creates a vector of ArrayList element. 

Code:

AddAnotherCollection.java

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class AddAnotherCollection {
public static void main(String[] arr) {
	// create a ArrayList object
	ArrayList obArrayList = new ArrayList();
	// add element in arraylist
	obArrayList.add(1);
	obArrayList.add(2);
	obArrayList.add(3);
	obArrayList.add(4);
	// Create iterator of arraylist element
	Iterator obIter = obArrayList.iterator();
	System.out.println("Elements of array list.");
	while (obIter.hasNext()) {
		System.out.print(obIter.next() + " ");
	}
	// Create a vector that contains elements of given collection
	Vector obVector = new Vector(obArrayList);
	System.out.println("\nElements in vector class.");
	// Enumeration of vector elements
	Enumeration obEnum = obVector.elements();
	while (obEnum.hasMoreElements()) {
		System.out.print(obEnum.nextElement() + " ");
	}
    }
}
Output:
Elements of array list.
1 2 3 4
Elements in vector class.
1 2 3 4

Download this code.
Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics