Difference Between a Vector and an Array

What is the difference between a Vector and an Array. Discuss the advantages and disadvantages of both?

The vector container class generalizes the concept of an ordinary C array. Like an array, a vector is an indexed data structure, with index values that range from 0 to one less than the number of elements contained in the structure. Also like an array, values are most commonly assigned to and extracted from the vector using the subscript operator. However, the vector differs from an array in the following important respects:

The size of the vector can change dynamically. New elements can be inserted on to the end of a vector, or into the middle. It is important to note, however, that while these abilities are provided, insertion into the middle of a vector is not as efficient as insertion into the middle of a list.

A vector has more "self-knowledge" than an ordinary array. In particular, a vector can be queried about its size, about the number of elements it can potentially hold (which may be different from its current size), and so on.

A vector can only hold references to objects and not primitive types.

Vector Implementaions are usually slower then array because of all the functionality that comes with them. As implemented in Java, vector is a thread-safe class and hence all methods are synchronous methods, which makes them considerably slow.

Note:

ArrayList has no default size. 

Vector has a default size of 10.

e.g.

import java.util.ArrayList; 
import java.util.Vector; 

public class TestList 

    public static void main(String args[]) 
    { 
        ArrayList al = new ArrayList(); 
        Vector v = new Vector(); 

        System.out.println("ArrayList Intial Size : " + al.size()); 

        System.out.println("Vector Intial size is : " + v.size()); 
        System.out.println("Vector Default Capacity  : " + v.capacity()); 
    } 

The Output is: 

ArrayList Intial Size : 0 
Vector Intial size is : 0 
Vector Default Capacity : 10 

The default capacity of vector is 10. 

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.