×

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java

In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable differences in their implementation.

ArrayList

The built-in array available in Java has a drawback. We cannotchange its size once wehave declared it. ArrayList overcomes this drawback. ArrayList is a class declared in java.util package. It is resizable and can increment its size by 50% if the number of elements exceed.

The following operations can be performed on an ArrayList:

  1. Adding new elements to ArrayList
  2. Accessing elements of ArrayList
  3. Changing elements of ArrayList
  4. Removing elements from ArrayList

The following program demonstrates how to implementthe above operations,

SampleArrayList.java

 import java.util.ArrayList;
public class SampleArrayList
{
    /* Driver Code */
public static void main(String ar[])
    {
    /* ArrayList Creation */
ArrayList<String> cities = new ArrayList<>();
    /* Adding elements to ArrayList */
cities.add("Kolkata");
cities.add("Delhi");
cities.add("Mumbai");
System.out.println("Initial ArrayList: " + cities);
    /* Adding elements using add() method */
cities.add(1, "Chennai");
System.out.println("After adding new element: " + cities);
    /* Accessing elements using get() method */
    String c1 = cities.get(1);
System.out.println("Accessing element at index 1: " + c1);
    /* changing the element using set() method */
cities.set(2, "Banglore");
System.out.println("After updating: " + cities);
    /* Removing element from index 2 using remove() method */
    String str1 = cities.remove(2);
System.out.println("After deletion: " + cities);
    /* Accessing elements of ArrayList using for-each loop */
System.out.println("Accessing individual elements:  ");
    for (String c : cities)
    {
System.out.print(c);
System.out.print(" ");
    }
  }
} 

Output:

 Initial ArrayList: [Kolkata, Delhi, Mumbai]
After adding new element: [Kolkata, Chennai, Delhi, Mumbai]
Accessing element at index 1: Chennai
After updating: [Kolkata, Chennai, Banglore, Mumbai]
After deletion: [Kolkata, Chennai, Mumbai]
Accessing individual elements: 
Kolkata Chennai Mumbai 

In the above code snippet, an ArrayListcities is declared inside SampleArrayList class and different operations are performed on it using the method available in theArrayList class.

Vector

The Vector class is just like the ArrayList but with a few differences. The size of the vector object is increased by double when new elements are added. All the methods in the Vector class are synchronized which means only one thread can work on the vector object at once. Hence it makes Vector slower as compare to the ArrayList.

The following operations can be performed on an ArrayList:

  1. Adding new elements to Vector
  2. Accessing elements of Vector
  3. Changing elements of Vector
  4. Removing elements from Vector

The following program demonstrates how to implement the above operations,

SampleVector.java

 import java.util.Vector;
import java.util.Iterator;
public class SampleVector
{
    /* Driver Code */
    public static void main(String[] args)
    {
        /* Creating a Vector */
        Vector<String>colors= new Vector<>();
        /* Adding elements to Vector using add() method */
colors.add("Blue");
colors.add("Red");
        /* Adding element using index number */
colors.add(2, "Yellow");
System.out.println("Vector: " + colors);
        /* Adding element using addAll() method */
        Vector<String> colors2 = new Vector<>();
colors.add("White");
        colors2.addAll(colors);
System.out.println("New Vector: " + colors2);
        /* Accessing elements using get() method */
        String element = colors.get(2);
System.out.println("Element at index 2: " + element);
        /* Accessing elements using iterator() */
        Iterator<String> iterate = colors.iterator();
System.out.print("Accessing individual elements: ");
        while(iterate.hasNext())
        {
System.out.print(iterate.next());
System.out.print(" ");
        }
System.out.println();
         /* Removing element using remove() method */
        String element1 = colors.remove(1);
System.out.println("Removed Element: " + element1);
System.out.println("New Vector: " + colors);
        /* Removing all the elements of Vector using clear() method */
colors.clear();
System.out.println("Vector after clear(): " + colors);
    }
} 

Output:

 Vector: [Blue, Red, Yellow]
New Vector: [Blue, Red, Yellow, White]
Element at index 2: Yellow
Accessing individual elements: Blue Red Yellow White
Removed Element: Red
New Vector: [Blue, Yellow, White]
Vector after clear(): [] 

In the above code snippet, a vector colors is declared inside SampleVector class and different operations are performed on it using the method available in the Vector class.

ArrayList Vs Vector

Sr. No.ArrayListVector
1.An ArrayList is a non-synchronized data structure that is used to store elements asa dynamic array.A Vector is a synchronized data structure that is used to store elements as a dynamic array.
2.The elements in the ArrayList are traversed using the Iterator interface.The elements in Vector are traversed using the Iterator or Enumeration interface.
3.Increases the array size by 50% if a number of elements are incremented.Increases the array size by 100% i.e., doubles, if number of elements are incremented.
4.ArrayList works faster compared to Vector.Vector works slower compared to ArrayList
5.ArrayList is not a legacy class.Vector is a legacy class.
6.ArrayList is used in single-user applications.Vector is used in multi-user applications.
7.ArrayList is not Thread-safe because multiple threads can access the ArrayList simultaneously.Vector is Thread safe because at any time only one thread is allowed to access the Vector object.

In this article, we have discussed ArrayList and Vector classes in Java and also compared both these classes.


Related Topics

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.