×

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

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 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.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.