Vector example in Java

By: Grenfel Emailed: 1745 times Printed: 2432 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Vector implements a dynamic array. It is similar to ArrayList, but with two differences:  Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. With the release of Java 2, Vector was reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections.

Here are the Vector constructors:

Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)

The first form creates a default vector, which has an initial size of 10. The second form creates a vector whose initial capacity is specified by size. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward. The fourth form creates a vector that contains the elements of collection c. This constructor was added by Java 2.

All vectors start with an initial capacity. After this initial capacity is reached, the next time that you attempt to store an object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. By allocating more than just the required memory, the vector reduces the number of allocations that must take place. This reduction is important, because allocations are costly in terms of time. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector. If you don't specify an increment, the vector's size is doubled by each allocation cycle.

Vector defines these protected data members:

int capacityIncrement;
int elementCount;
Object elementData[ ];

The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in elementCount. The array that holds the vector is stored in elementData.

Because Vector implements List, you can use a vector just like you use an ArrayList instance. You can also manipulate one using its legacy methods. For example, after you instantiate a Vector, you can add an element to it by calling addElement( ). To obtain the element at a specific location, call elementAt( ). To obtain the first element in the vector, call firstElement( ). To retrieve the last element, call lastElement( ). You can obtain the index of an element by using indexOf( ) and lastIndexOf( ). To remove an element, call removeElement( ) or removeElementAt( ).

The following program uses a vector to store various types of numeric objects. It demonstrates several of the legacy methods defined by Vector. It also demonstrates the Enumeration interface.

//Demonstrate various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

The output from this program is shown here:

Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

With the release of Java 2, Vector adds support for iterators. Instead of relying on an enumeration to cycle through the objects (as the preceding program does), you now can use an iterator. For example, the following iterator-based code can be substituted into the program:

// use an iterator to display contents
Iterator vItr = v.iterator();
System.out.println("\\nElements in vector:");
while(vItr.hasNext())
System.out.print(vItr.next() + " ");
System.out.println();

Because enumerations are not recommended for new code, you will usually use an iterator to enumerate the contents of a vector. Of course, much legacy code exists that employs enumerations. Fortunately, enumerations and iterators work in nearly the same manner.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(28)


1. View Comment

Good To understand.

View Tutorial          By: Radhika at 2010-05-11 01:24:55
2. View Comment

A very good demonstration o Vector!!

View Tutorial          By: Pankaj Kumar Mishra at 2010-12-09 01:35:06
3. View Comment

i need table example!!!...

View Tutorial          By: Sadyog at 2011-01-03 21:59:09
4. View Comment

Good one!!!!!!!!

View Tutorial          By: Manya at 2011-06-30 11:59:25
5. View Comment

Good example for vector

View Tutorial          By: mangai at 2011-07-07 09:46:10
6. View Comment

thanks it is nice

View Tutorial          By: Ajay at 2011-07-22 03:44:05
7. View Comment

if the simple example with syntex than very easy to understand
it also better.


View Tutorial          By: Rikunj suthar at 2011-08-31 06:57:17
8. View Comment

This is very useful for java beginners

View Tutorial          By: Syed Musthafa at 2011-11-20 07:11:50
9. View Comment

better..................
implements...........


View Tutorial          By: sunny at 2012-01-04 17:30:12
10. View Comment

nice one

View Tutorial          By: dhusor at 2012-05-08 17:38:50
11. View Comment

Excellent for beginners

View Tutorial          By: PRN at 2012-05-22 09:49:15
12. View Comment

Excellent example

View Tutorial          By: Dinesh Patil at 2012-06-19 08:30:48
13. View Comment

Hi Grenfel, would this be possible??

public void readFile() throws IOException{
cars = new CarRecordManager("hondaInventory.txt");
cars = new CarRecordManager("toyotaInventory.txt");
cars = new CarRecordManager("fordInventory.txt");

Vector<Object> carList = new Vector<Object>();
carList.add(cars);
}


View Tutorial          By: Lerianne at 2012-08-20 11:37:32
14. View Comment

thanks a lot fo the help offered.

View Tutorial          By: Douglas Olupotdolupot@cit.mak.ac.ug at 2012-10-31 05:37:04
15. View Comment

thanks i understood

View Tutorial          By: raksha at 2012-11-04 16:44:19
16. View Comment

the example is from herbert schildt complete ref...

View Tutorial          By: dui_prithibi at 2012-11-26 12:59:15
17. View Comment

it's very helpful for java beginner. thanks

View Tutorial          By: Pisal at 2012-12-03 05:00:54
18. View Comment

thanks

View Tutorial          By: snooker at 2013-02-04 19:45:40
19. View Comment

Hi sir, Your explain is very good sir,

View Tutorial          By: Surendra Majji at 2013-02-14 04:55:49
20. View Comment

Easy to understand.......

View Tutorial          By: Priya at 2013-02-15 10:55:52
21. View Comment

very Good machi.......

View Tutorial          By: Janani at 2013-03-04 06:37:47
22. View Comment

Thank you......

View Tutorial          By: Suvadip at 2013-04-19 05:11:51
23. View Comment

Thank you! Nice article.

View Tutorial          By: Koja at 2013-04-23 20:58:05
24. View Comment

Isn't the Vector class deprecated now? I think ArrayList is the
preferred class, since it allows generics.


View Tutorial          By: Brent at 2013-07-07 06:10:01
25. View Comment

Can anybody tell.... what if condition is doing in this program
???


View Tutorial          By: Randhir Sambyal at 2013-08-26 06:37:25
26. View Comment

you have helped me so much! thanks a lot ya! i really loved it. now i can code a program using vectors. God bless uuuuuu

View Tutorial          By: NATION WHITE CHIRARA at 2013-09-19 07:53:57
27. View Comment

HI Friends,

I am new to java and i have one small doubt. In the above program we are passing as v.addElement(new Integer(1)) and i written in method as v.addElement(45) and it is working fine. Can one explain what is the difference here.


View Tutorial          By: Srini at 2015-04-05 17:00:58
28. View Comment

@Srini

Hi Srini, I can answer your query. Its a concept in java called autoboxing if you pass any primitive datatype instead of object (eg. int data ie, 45 intead of Integer class object) it will automatically converted to object type and vice versa.

I hope you understood this.

Thank you.


View Tutorial          By: Sudev Wilson at 2015-04-08 12:23:33

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Grenfel
Verifying a Signed JAR File example
Bitwise and Bit Shift Operators example in Java
JavaBeans Basic Concepts
The Differences Between Simple and Classic Tags in JSP
Bitwise Logical Operators in C
DispatchAction in Struts
union example program in C
Comparison operators in JSP
Basics of Structures in C
register Variables in C
Struts and Tiles - Steps to use Struts and Tiles
The if else statement in C
Character Counting sample program in C
Installing JSF
cin.ignore() in C++

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
The Basic Structure of a Simple Java program
What is Java?
Stack example in Java - push(), pop(), empty(), search()
Count number of vowels, consonants and digits in a String in Java
Using StringTokenizer in Java
wait(), notify() and notifyAll() in Java - A tutorial
Student marks calculation program in Java
InetAddress Example program in Java
FileReader and FileWriter example program in Java
append() in Java
Integer: byte, short, int, and long data types in Java
Method Overriding in Java
Read from a COM port using Java program
Most Emailed Articles (in Java)
Update contents of a file within a jar file
Java Chat Client Sample Applet
Execute system commands in a Java Program
Get user input in Java
Reading from a file and writing to a file using Java program
ThreadGroup Sample in Java
String Concatenation using Java
J2EE Services
Insert, Delete, Search, Print an int Array in Java
Text to Speech conversion program in Java
Major components of FxObjects in JavaFX
How to use and access the inner class in java
History of Java
Importing a Certificate for the CA example using keytool in Java
Using continue Statement - example in Java