×

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

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.