Key differences between ArrayList and Vector in Java

ArrayList in Java

ArrayList in Java is a resizable array implementation of the List interface, part of the Java Collections Framework. It provides a way to store elements dynamically, allowing the list to grow or shrink as needed. Unlike standard arrays, which have a fixed size, ArrayList can adjust its size automatically when elements are added or removed. This feature makes it a flexible and popular choice for managing collections of objects where the total number or order of elements may change frequently.

ArrayList allows duplicate elements and maintains the order of insertion. Elements can be accessed directly by their index, offering constant-time positional access. However, adding or removing elements from anywhere other than the end of the list requires shifting elements, which can be slower than operations on some other list types. ArrayList also provides methods for common operations like searching, sorting, and iterating through the list.

Functions of ArrayList in Java:

  • Dynamic Resizing:

Automatically resizes itself when elements are added or removed.

  • Add Elements:

Supports adding elements at the end of the list (add(E e)) or at a specified index (add(int index, E element)).

  • Remove Elements:

Allows removal of elements either by index (remove(int index)) or by object (remove(Object o)).

  • Access Elements:

Provides direct access to elements via their index (get(int index)).

  • Modify Elements:

Enables setting the value of elements at a specific index (set(int index, E element)).

  • Size of List:

Can return the number of elements in the list (size()).

  • Check if Empty:

Checks whether the list is empty (isEmpty()).

  • Iterate Over Elements:

Supports iterators and can be used in enhanced for loops.

  • Sort List:

Can sort the elements within the list using Collections.sort(List<T>).

  • Search:

Provides mechanisms to search for elements, including binary search with the help of Collections class.

  • Sublist:

Creates a view of a portion of the original list (subList(int fromIndex, int toIndex)).

  • Conversion to Array:

Can be converted into a standard array (toArray()).

  • Clear All Elements:

Removes all elements from the list (clear()).

  • Contains Element:

Checks if the list contains a specified element (contains(Object o)).

  • Bulk Operations:

Includes methods like addAll, removeAll, and retainAll for performing bulk operations on collections.

Example of ArrayList in Java:

This example covers basic operations like adding, removing, and iterating over elements in an ArrayList.

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        // Creating an ArrayList of String type

        ArrayList<String> fruits = new ArrayList<>();

        // Adding elements to the ArrayList

        fruits.add(“Apple”);

        fruits.add(“Banana”);

        fruits.add(“Cherry”);

        fruits.add(“Date”);

        // Printing all elements using enhanced for loop

        System.out.println(“List of fruits:”);

        for (String fruit : fruits) {

            System.out.println(fruit);

        }

        // Removing an element from the ArrayList

        fruits.remove(“Banana”); // removing by object

        fruits.remove(1); // removing by index (removes “Cherry”)

        // Adding an element at a specific position

        fruits.add(0, “Elderberry”);

        // Accessing elements by index

        System.out.println(“First fruit in the list: ” + fruits.get(0));

        // Replacing an element

        fruits.set(1, “Fig”);

        // Checking if the ArrayList contains an item

        if (fruits.contains(“Apple”)) {

            System.out.println(“Apple is in the list.”);

        }

        // Printing the modified list

        System.out.println(“Updated list of fruits:”);

        for (String fruit : fruits) {

            System.out.println(fruit);

        }

        // Getting the size of the ArrayList

        System.out.println(“The list has ” + fruits.size() + ” fruits.”);

       

        // Clearing all elements

        fruits.clear();

        System.out.println(“After clearing, the list has ” + fruits.size() + ” fruits.”);

    }

}

This example illustrates how to create an ArrayList, add items, remove items, access items, check for items, and modify items. The ArrayList is also cleared at the end of the example to demonstrate removing all elements from it.                           

Vector in Java

Vector class in Java is part of the Java Collection Framework and represents a dynamically resizable array of objects. Similar to ArrayList, it provides the ability to store and manipulate a list of objects. However, unlike ArrayList, all methods in Vector are synchronized, which makes it thread-safe but generally results in poorer performance in single-threaded scenarios. Introduced in Java 1.0, Vector automatically doubles its size when its capacity is exceeded, although this increment behavior can be customized.

Despite its thread-safety feature, Vector is considered somewhat legacy and is less preferred compared to other modern alternatives like ArrayList or CopyOnWriteArrayList in concurrent environments, primarily due to its performance overhead from unnecessary synchronization when thread safety is not required. Nevertheless, it remains useful in applications where a simple, thread-safe, dynamic array implementation is needed.

Functions of ArrayList in Java:

  • Dynamic Resizing:

Automatically resizes itself as elements are added or removed.

  • Random Access:

Provides constant-time positional access to elements.

  • Addition and Removal:

Supports adding and removing elements both at the end of the list and at specific positions.

  • Iteration:

Supports various ways of iterating over the elements, including iterators and enhanced for-loops.

  • Manipulation:

Offers methods to manipulate the entire list, such as sort, clear, isEmpty, indexOf, and contains.

  • Bulk Operations:

Methods like addAll, removeAll, and retainAll allow for bulk operations on collections.

  • Sublists:

Allows creation of a dynamically connected sublist, which reflects changes in the main list.

  • Serialization:

Implements the Serializable interface, allowing it to be used in serialization streams.

Example of ArrayList in Java:

This example demonstrates creating an ArrayList, adding elements, removing an element, and iterating through the list to print out the elements.

import java.util.ArrayList;

public class ExampleArrayList {

    public static void main(String[] args) {

        // Creating an ArrayList of String type

        ArrayList<String> colors = new ArrayList<String>();

        // Adding elements to the ArrayList

        colors.add(“Red”);

        colors.add(“Blue”);

        colors.add(“Green”);

        colors.add(“Yellow”);

        // Displaying the ArrayList elements

        System.out.println(“Initial ArrayList: ” + colors);

        // Removing the element at index 2 (“Green”)

        colors.remove(2);

        // Displaying the ArrayList after removal

        System.out.println(“ArrayList after removing Green: ” + colors);

        // Iterating over ArrayList elements using enhanced for-loop

        System.out.println(“Current ArrayList:”);

        for (String color : colors) {

            System.out.println(color);

        }

    }

}

Output:

Initial ArrayList: [Red, Blue, Green, Yellow]

ArrayList after removing Green: [Red, Blue, Yellow]

Current ArrayList:

Red

Blue

Yellow

This example covers the basics of using an ArrayList such as adding and removing elements, and iterating through the list to display its contents. It highlights the ease of managing dynamic arrays in Java using ArrayList.

Key differences between ArrayList and Vector in Java

Aspect ArrayList Vector
Synchronization Not synchronized Synchronized
Thread Safety Not thread-safe Thread-safe
Performance Faster Slower due to synchronization
Initial Capacity Grows from default 10 Starts at default 10
Capacity Increment Grows 50% of current size Doubles by default
Method of synchronization Manually via Collections.synchronizedList Inherently synchronized
Best Use Case Non-threaded applications Threaded applications
Iteration Safety Fail-fast Fail-fast
Introduced in Java 2, JDK 1.2 Java 1.0
Size Increase Increases as needed Doubles or by specified increment
Memory Efficiency More memory efficient Less memory efficient due to extra overhead
API Richness Part of Collections Framework Legacy, less used in new code
Output Iterator Iterator Enumeration and Iterator
Frequency of Use in Modern Java More common Less common, legacy
Locking Mechanism No intrinsic locking Intrinsic locking on every method

Key Similarities between ArrayList and Vector in Java

  • Data Structure Type:

Both are implementations of the List interface in the Java Collections Framework, meaning they are both designed to store an ordered collection of elements.

  • Resizable Arrays:

They dynamically expand to accommodate additional elements as needed. This means you do not need to specify an initial size that limits the number of elements they can hold.

  • Element Access:

Both support random access to elements via an index, making them efficient for scenarios where frequent access to elements via their index is required.

  • Element Operations:

They provide similar functionalities for adding, removing, and accessing elements. Methods like add(), remove(), get(), and set() are common to both.

  • Null Elements:

They both allow null elements, making them versatile for collections that may include optional or undefined values.

  • Duplicate Elements:

Both classes allow duplicate elements, so you can insert the same object or value multiple times.

  • Order Preservation:

They maintain the insertion order of elements, which means they keep the elements in the order they were added.

  • Iterability:

Both provide iterators and can be used in enhanced for loops (for-each loop) to iterate through the elements.

error: Content is protected !!