[Go to site: main page, start]

0% found this document useful (0 votes)
9 views7 pages

Java Vector Class Overview

The document provides an overview of the Java Vector class, which implements a dynamic array that is synchronized and includes legacy methods not found in the collections framework. It details the class declaration, constructors, and various methods available for manipulating Vector objects. Additionally, it includes an example program demonstrating how to add elements and iterate through a Vector.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views7 pages

Java Vector Class Overview

The document provides an overview of the Java Vector class, which implements a dynamic array that is synchronized and includes legacy methods not found in the collections framework. It details the class declaration, constructors, and various methods available for manipulating Vector objects. Additionally, it includes an example program demonstrating how to add elements and iterate through a Vector.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Page 1 of 9

Home Whiteboard AI Assistant Online Compilers Jobs Tools Art

SQL HTML CSS Javascript Python Java C C++ PHP Scala C#

Java Vector Class

Introduction
Vector implements a dynamic array. It is similar to ArrayList, but with two differences −

Vector is synchronized.

Vector contains many legacy methods that are not part of the collections
framework.

Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program.

The [Link] class implements a growable array of objects. Similar to an Array,


it contains components that can be accessed using an integer index. Following are the
important points about Vector −

The size of a Vector can grow or shrink as needed to accommodate adding and
removing items.

Each vector tries to optimize storage management by maintaining a capacity and


a capacityIncrement.

As of the Java 2 platform v1.2, this class was retrofitted to implement the List
interface.

Unlike the new collection implementations, Vector is synchronized.

This class is a member of the Java Collections Framework.

Class declaration
Following is the declaration for [Link] class −
Page 2 of 9

public class Vector<E>


extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

Here <E> represents an Element, which could be any class. For example, if you're
building an array list of Integers then you'd initialize it as follows −

ArrayList<Integer> list = new ArrayList<Integer>();

Class constructors

[Link]. Constructor & Description

Vector()
1 This constructor is used to create an empty vector so that its internal data
array has size 10 and its standard capacity increment is zero.

Vector(Collection<? extends E> c)


2 This constructor is used to create a vector containing the elements of the
specified collection, in the order they are returned by the collection's iterator.

Vector(int initialCapacity)
3 This constructor is used to create an empty vector with the specified initial
capacity and with its capacity increment equal to zero.

Vector(int initialCapacity, int capacityIncrement)


4 This constructor is used to create an empty vector with the specified initial
capacity and capacity increment.

Class methods

[Link]. Method & Description

boolean add(E e)
1
This method appends the specified element to the end of this Vector.

boolean addAll(Collection<? extends E> c)


2 This method appends all of the elements in the specified Collection to the end
of this Vector.

void addElement(E obj)


3 This method adds the specified component to the end of this vector,
increasing its size by one.
Page 3 of 9

int capacity()
4
This method returns the current capacity of this vector.

void clear()
5
This method removes all of the elements from this vector.

Vector clone()
6
This method returns a clone of this vector.

boolean contains(Object o)
7
This method returns true if this vector contains the specified element.

boolean containsAll(Collection<?> c)
8 This method returns true if this Vector contains all of the elements in the
specified Collection.

void copyInto(Object[ ] anArray)


9
This method copies the components of this vector into the specified array.

E elementAt(int index)
10
This method returns the component at the specified index.

Enumeration<E> elements()
11
This method returns an enumeration of the components of this vector.

void ensureCapacity(int minCapacity)


This method increases the capacity of this vector, if necessary, to ensure that
12
it can hold at least the number of components specified by the minimum
capacity argument.

boolean equals(Object o)
13
This method compares the specified Object with this Vector for equality.

E firstElement()
14
This method returns the first component (the item at index 0) of this vector.

void forEach(Consumer<? super E> action)


15 This method performs the given action for each element of the Iterable until
all elements have been processed or the action throws an exception.

E get(int index)
16
This method returns the element at the specified position in this Vector.

int hashCode()
17
This method returns the hash code value for this Vector.

18 int indexOf(Object o)
Page 4 of 9

This method returns the index of the first occurrence of the specified element
in this vector, or -1 if this vector does not contain the element.

void insertElementAt(E obj, int index)


19 This method inserts the specified object as a component in this vector at the
specified index.

boolean isEmpty()
20
This method tests if this vector has no components.

Iterator<E> iterator()
21 This method returns an iterator over the elements in this list in proper
sequence.

E lastElement()
22
This method returns the last component of the vector.

int lastIndexOf(Object o)
23 This method returns the index of the last occurrence of the specified element
in this vector, or -1 if this vector does not contain the element.

ListIterator<E> listIterator()
24 This method returns a list iterator over the elements in this list (in proper
sequence).

E remove(int index)
25
This method removes the element at the specified position in this Vector.

boolean removeAll(Collection<?> c)
26 This method removes from this Vector all of its elements that are contained
in the specified Collection.

void removeAllElements()
27 This method removes all components from this vector and sets its size to
zero.

boolean removeElement(Object obj)


28
This method removes the first occurrence of the argument from this vector.

void removeElementAt(int index)


29
This method deletes the component at the specified index.

boolean removeIf(Predicate<? super E> filter)


30
Removes all of the elements of this collection that satisfy the given predicate.

boolean retainAll(Collection<?> c)
31 This method retains only the elements in this Vector that are contained in the
specified Collection.
Page 5 of 9

E set(int index, E element)


32 This method replaces the element at the specified position in this Vector with
the specified element.

void setElementAt(E obj, int index)


33 This method sets the component at the specified index of this vector to be
the specified object.

void setSize(int newSize)


34
This method sets the size of this vector.

int size()
35
This method returns the number of components in this vector.

Spliterator<E> spliterator()
36
Creates a late-binding and fail-fast Spliterator over the elements in this list.

List <E> subList(int fromIndex, int toIndex)


37 This method returns a view of the portion of this List between fromIndex,
inclusive, and toIndex, exclusive.

object[] toArray()
38 This method returns an array containing all of the elements in this Vector in
the correct order.

String toString()
39 This method returns a string representation of this Vector, containing the
String representation of each element.

void trimToSize()
40
This method trims the capacity of this vector to be the vector's current size.

Methods inherited
This class inherits methods from the following classes −

[Link]

[Link]

[Link]

Adding Elements and Iterating a Vector Example


The following program illustrates several of the methods supported by Vector collection −
Page 6 of 9

Open Compiler

import [Link].*;
public class VectorDemo {

public static void main(String args[]) {


// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
[Link]("Initial size: " + [Link]());
[Link]("Initial capacity: " + [Link]());

[Link](new Integer(1));
[Link](new Integer(2));
[Link](new Integer(3));
[Link](new Integer(4));
[Link]("Capacity after four additions: " + [Link]());

[Link](new Double(5.45));
[Link]("Current capacity: " + [Link]());

[Link](new Double(6.08));
[Link](new Integer(7));
[Link]("Current capacity: " + [Link]());

[Link](new Float(9.4));
[Link](new Integer(10));
[Link]("Current capacity: " + [Link]());

[Link](new Integer(11));
[Link](new Integer(12));
[Link]("First element: " + (Integer)[Link]());
[Link]("Last element: " + (Integer)[Link]());

if([Link](new Integer(3)))
[Link]("Vector contains 3.");

// enumerate the elements in the vector.


Enumeration vEnum = [Link]();
[Link]("\nElements in vector:");

while([Link]())
[Link]([Link]() + " ");
Page 7 of 9

[Link]();
}
}

This will produce the following result −

Output

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

TOP TUTORIALS

Python Tutorial
Java Tutorial

C++ Tutorial
C Programming Tutorial
C# Tutorial

PHP Tutorial
R Tutorial
HTML Tutorial

CSS Tutorial
JavaScript Tutorial
SQL Tutorial

TRENDING TECHNOLOGIES

Common questions

Powered by AI

To ensure that a Vector can hold at least a certain number of elements without resizing, you can use the `ensureCapacity(int minCapacity)` method. This method increases the capacity of the Vector, if necessary, to ensure that it can accommodate the specified minimum number of elements. By calling this method before adding elements, you can avoid the overhead associated with automatic resizing due to repeated capacity expansions during element additions .

The primary differences between the Java Vector class and the ArrayList class are synchronization and legacy support. Vector is synchronized, meaning it is thread-safe and can be safely accessed by multiple threads concurrently; however, this comes at the cost of performance due to the overhead of synchronization. In contrast, ArrayList is unsynchronized, offering better performance in single-threaded contexts . Additionally, Vector is part of the legacy collection classes and contains methods that are not part of the new collections framework, whereas ArrayList is part of the Java Collections Framework introduced later, aligning better with modern Java programming practices .

The `listIterator()` method in the context of the Vector class serves the purpose of returning a list iterator over the elements in this list, allowing for bidirectional iteration and modification. This iterator supports operations such as next, previous, add, remove, and set, making it a powerful tool for traversing and manipulating the elements of the Vector. The ability to iterate and modify while traversing is particularly useful for applications requiring navigation and dynamic updates within the collection . This method benefits from the synchronized nature of Vector when used in concurrent modification scenarios .

Using `setSize(int newSize)` directly affects the internal representation and capacity of a Vector. If `newSize` is greater than the current size, the method increases the Vector's size by appending null elements until it reaches the specified new size, potentially requiring a capacity increase. If `newSize` is less than the current size, elements past the new size index are discarded, effectively reducing the Vector's size without constraining its capacity, which can still exceed the current size of elements . This method allows direct resizing, but care must be taken in understanding that it modifies the list without preserving element data beyond the new size .

Using `removeElementAt(int index)` on a large Vector can have significant performance implications due to the way the method operates. Since Vector maintains elements in an array-like structure, removing an element necessitates shifting all subsequent elements one position to the left, which can be an O(n) operation where n is the number of elements in the Vector. This makes removal operations potentially costly in terms of performance, especially for large Vectors or frequent removals . Consequently, for scenarios involving frequent removals, an alternative data structure such as LinkedList might be more suitable .

The `trimToSize()` method in the Vector class is significant for optimizing memory usage by reducing the capacity of the Vector to match its current size. This method can be particularly useful after a large number of elements have been removed, and you want to release unused memory back to the system. It is recommended to use `trimToSize()` when the Vector is not expected to grow significantly in size in the near future, as this operation may help reduce the memory footprint of the application, albeit at the expense of potential performance overhead if the Vector subsequently needs to increase in size again .

The methods `elementAt(int index)` and `get(int index)` provide similar functionality in the Java Vector class as both return the element at the specified index. However, `elementAt()` is a legacy method that predates the introduction of the Java Collections Framework, whereas `get()` is part of the modern List interface implemented by Vector. Despite their similar operation, using `get()` is recommended for code consistency with other List implementations .

The Java Vector class manages dynamic resizing by maintaining a capacity and a capacityIncrement. When elements are added and exceed the current capacity, the Vector automatically increases its capacity. The default initial capacity of a Vector is 10, and if no capacityIncrement is specified, the capacity is doubled each time additional space is required. This strategy optimizes storage management by ensuring efficient use of memory .

The `synchronized` nature of the Vector class affects concurrent access by providing built-in thread safety, ensuring that only one thread can access and modify the Vector at a time, thereby preventing data inconsistency and race conditions in multi-threaded environments. While this makes Vector safe for concurrent access, it also introduces performance overhead due to the locking mechanism required for synchronization, potentially making operations slower compared to non-synchronized collections like ArrayList. Consequently, in situations where high concurrency and performance are critical, using a non-blocking data structure or external synchronization (e.g., using Collections.synchronizedList with ArrayList) might be more appropriate .

The `clone()` method of a Vector can be particularly useful in scenarios where you need to create a shallow copy of the Vector, preserving the current state including all elements at a specific point in time. This is useful when you want to work with a snapshot of the Vector's data without affecting the original Vector, such as in undo functionality implementation or when passing data to other parts of a program that should not modify the original Vector data . However, it's important to note that `clone()` performs a shallow copy, meaning that the elements themselves are not duplicated unless they are immutable or explicitly cloned themselves .

You might also like