Java List Interfaces And Implementations

In Java, the List interfaces is a fundamental part of the Collections Framework. It represents an ordered collection of elements, allowing duplicates and providing various operations to manipulate and access the elements. The List interface in Java represents an ordered collection of elements. It extends the Collection interface and adds specific operations for working with lists. Lists allow duplicates, and their elements are ordered by their insertion sequence.

Key Features Of Java List Interfaces

  • Ordering: Lists maintain the order of elements as they are inserted.
  • Duplicates: Lists allow duplicate elements to be present in the collection.
  • Index-Based Access: Elements in a list can be accessed using their index positions.
  • Dynamic Size: Lists can dynamically grow or shrink as elements are added or removed.
  • Iteration: Lists can be iterated using various techniques such as loops or iterators.

Benefits Of Using the Java List Interfaces

  • Flexibility: Lists provide flexibility in managing collections of elements with ordered access.
  • Manipulation: The List interface offers methods to add, remove, and modify elements.
  • Index-Based Operations: Lists allow efficient random access to elements using their indices.
  • Iteration: Lists support easy traversal and iteration through the elements.

Declaration Of Java List Interfaces

public interface List<E> extends Collection; 

Since List is just an interface and objects cannot be created of a List type. We need a class that implements the List interface in order to create its object. Just like several other user-defined `interfaces` implemented by user-defined `classes`, List is an `interface`, implemented by several classes such as `ArrayList`, `LinkedList`, `Vector`, and `Stack` class, pre-defined in java.util package. Let’s have a look at its hierarchy.

Hierarchy Of List 

List: The List interface is the base interface that represents an ordered collection of elements. It allows for duplicate elements and provides methods for adding, removing, and accessing elements based on their index.

ArrayList: The ArrayList class is an implementation of the List interface that uses a dynamic array to store the elements. It provides fast random access to elements but may be slower when performing frequent insertions or deletions.

LinkedList: The LinkedList class is another implementation of the List interface that uses a doubly-linked list to store the elements. It provides efficient insertion and deletion operations, but accessing elements by index may be slower compared to ArrayList.

Vector: The Vector class is a legacy implementation of the List interface that is similar to ArrayList. It is synchronized, which means it is thread-safe but may have a performance impact in multi-threaded scenarios.

Stack: The Stack class extends the Vector class and represents a last-in-first-out (LIFO) stack of elements. It provides additional methods like push and pop for stack-specific operations.

Hierarchy Of List 

Methods Of Java List Interfaces

MethodDescription
public boolean add(E element)Appends the specified element to the end of the list.
public void add(int index, E element)Inserts the specified element at the specified position.
public boolean addAll(Collection c)Appends all elements in the specified collection to the end of the list.
public boolean addAll(int index, Collection c)Inserts all elements in the specified collection at the specified position.
public <E> get(int index)Returns the element at the specified position in the list.
public <E> set(int index, E element)Replaces the element at the specified position in the list with the specified element.
public <E> remove(int index)Removes the element at the specified position in the list.
public boolean remove(Object o)Removes the first occurrence of the specified element from the list, if present.
public void clear()Removes all elements from the list.
public boolean contains(Object o)Returns true if the list contains the specified element.
public boolean isEmpty()Returns true if the list is empty.
public int size()Returns the number of elements in the list.
public int indexOf(Object o)Returns the index of the first occurrence of the specified element in the list, or -1 if not found.
public int lastIndexOf(Object o)Returns the index of the last occurrence of the specified element in the list, or -1 if not found.
public List subList(int fromIndex, int toIndex)Returns a new list containing elements from the specified fromIndex (inclusive) to the specified toIndex (exclusive).
public Iterator iterator()Returns an iterator over the elements in the list.
public ListIterator listIterator()Returns a list iterator over the elements in the list.
public ListIterator listIterator(int index)Returns a list iterator over the elements in the list, starting at the specified position.
public Object[] toArray()Returns an array containing all elements in the list.
public T[] toArray(T[] a)Returns an array containing all elements in the list, using the runtime type of the specified array.
public boolean containsAll(Collection c)Returns true if the list contains all elements in the specified collection.
public boolean removeAll(Collection c)Removes all elements in the list that are also present in the specified collection.
public boolean retainAll(Collection c)Retains only the elements in the list that are also present in the specified collection.
public boolean equals(Object o)Compares the specified object with the list for equality.
public int hashCode()Returns the hash code value for the list.

Operations On A Java List Interfaces

In the Java List interface, various operations can be performed to manipulate and access elements within a list. Here are some commonly used operations:

  1. Adding Elements:
  • `add(element)`: Appends the specified element to the end of the list.
  • `add(index, element)`: Inserts the specified element at the specified position.
  1. Removing Elements:
  • `remove(index)`: Removes the element at the specified position in the list.
  • `remove(element)`: Removes the first occurrence of the specified element from the list, if present.
  1. Updating Elements:
  • `set(index, element)`: Replaces the element at the specified position with the specified element.
  1. Checking if Element is Present:
  • `contains(element)`: Returns true if the list contains the specified element.
  • `indexOf(element)`: Returns the index of the first occurrence of the specified element in the list.
  • `lastIndexOf(element)`: Returns the index of the last occurrence of the specified element in the list.
  1. Accessing Elements:
  • `get(index)`: Returns the element at the specified position in the list.

For example, 

import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        // Creating a new ArrayList
        List myList = new ArrayList<>();

        // Adding elements to the list
        myList.add("Apple");
        myList.add("Banana");
        myList.add("Orange");

        // Updating an element at index 1
        myList.set(1, "Mango");

        // Checking if an element is present in the list
        boolean containsOrange = myList.contains("Orange");
        System.out.println("Does the list contain Orange? " + containsOrange);

        // Retrieving an element at index 2
        String fruit = myList.get(2);
        System.out.println("Element at index 2: " + fruit);

        // Removing an element at index 0
        myList.remove(0);

        // Removing an element by value
        boolean removed = myList.remove("Banana");
        System.out.println("Element 'Banana' removed? " + removed);

        // Checking the index of an element
        int index = myList.indexOf("Mango");
        System.out.println("Index of 'Mango': " + index);

        // Displaying the final list
        System.out.println("Final List: " + myList);
    }
}

Output:

Does the list contain Orange? true
Element at index 2: Orange
Element 'Banana' removed? true
Index of 'Mango': 0
Final List: [Mango]

Iterating Over List Interfaces In Java

  • Using a for loop: A simple and widely-used technique is to iterate over a List using a `for loop`. The loop variable represents the index, and you can access each element using the `get()` method.
  • Using an enhanced for loop (for-each loop): This technique provides a more concise syntax for iterating over a List. It automatically handles the iteration and retrieval of each element.
  • Using an iterator: The Iterator interface provides a way to iterate over a List and perform various operations like removal while iterating.
  • Using a ListIterator: The ListIterator interface extends the Iterator interface and provides additional functionality, such as traversing the List in both directions and modifying elements during iteration.

For example, 

List list = new ArrayList<>();

list.add("Apple");

list.add("Banana");

list.add("Orange");

// Traversing using a simple loop

for (int i = 0; i < list.size(); i++) {

    String element = list.get(i);

    System.out.println(element);

}

System.out.println();

// Traversing using for enhanced loop

for (String element: list) {

    System.out.println(element);

}

System.out.println();

// Traversing using the iterator

Iterator iterator = list.iterator();

while (iterator.hasNext()) {

    String element = iterator.next();

    System.out.println(element);

}

System.out.println();

// Traversing in forward direction

ListIterator iterator = list.listIterator();

while (iterator.hasNext()) {

    String element = iterator.next();

    System.out.println(element);

}

System.out.println();

// Traversing in reverse direction

while (iterator.hasPrevious()) {

    String element = iterator.previous();

    System.out.println(element);

}

Output:

Apple

Banana

Orange

Apple

Banana

Orange

Apple

Banana

Orange

Apple

Banana

Orange

Orange

Banana

Apple

Classes That Inherit From Java List Interfaces 

As we can clearly see in the hierarchy several classes inherit from the List Interface.  The Java List interface is implemented by several classes in the Java Collection Framework. 

ArrayList: ArrayList is an implementation of the List interface that provides a dynamic array-like structure. It is widely used due to its efficient random access and fast element retrieval. ArrayList allows for dynamic resizing, making it suitable for scenarios where frequent element insertion and removal operations are not required.

LinkedList: LinkedList is another implementation of the List interface that provides a doubly-linked list data structure. It is efficient for frequent insertions and removals at both ends of the list. LinkedList also offers additional methods for manipulating elements at the beginning and end of the list.

Vector: Vector is a legacy class that also implements the List interface. It is similar to ArrayList but provides synchronization, making it thread-safe. Vector is typically used in scenarios where multiple threads need to access and modify a list concurrently.

Stack: Stack is a subclass of Vector and represents a Last-In-First-Out (LIFO) data structure. It follows the push and pop operations, where elements are added and removed from the top of the stack, respectively.

Let’s study each class and the methods they offer and the operations that can be performed using these classes.

ArrayList In Java 

ArrayList is a class in Java that implements the List Interface and provides a dynamic array-like data structure. It is part of the Java Collections Framework and is commonly used to store and manipulate collections of objects. ArrayList offers several advantages over arrays, such as dynamic resizing, flexible insertion and removal of elements, and built-in methods for common operations. 

Key Features of ArrayList

  • Dynamic Size: Unlike arrays, ArrayList automatically adjusts its size as elements are added or removed. This allows for more flexible storage and eliminates the need to manually resize the array.
  • Random Access: ArrayList provides efficient random access to elements using their index. This allows for quick retrieval and modification of elements at any position within the list.
  • Collection Methods: ArrayList supports a wide range of methods for manipulating and accessing elements, such as adding, removing, searching, sorting, and iterating over the elements.
  • Iterable Interface: ArrayList implements the Iterable interface, which allows for easy iteration over the elements using enhanced for loops or iterators.

How to create and initialize the ArrayList

In Java, there are several ways to declare and initialize an ArrayList. Depending on your requirements and coding style, you can choose the approach that suits your needs. Let’s explore some common ways to declare and initialize an ArrayList:

  1. Declaration with the default constructor:

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

In this approach, we use the default constructor of `ArrayList` to create an empty `ArrayList` of type `String`. You can replace `String` with any other desired type.

  1. Declaration with initial capacity:

ArrayList<Integer> numbers = new ArrayList<>(10);

Here, we declare an ArrayList of type Integer with an `initial capacity` of `10`. This can be useful when you have an estimation of the number of elements you’ll be adding to the list.

  1. Declaration with values using Arrays.asList():

ArrayList<String> names = new ArrayList<>(Arrays.asList(“Alice”, “Bob”, “Charlie”));

In this approach, we use the `Arrays.asList()` method to create a List from an array of values, and then pass it to the `ArrayList` constructor. This allows us to directly initialize the `ArrayList` with the provided values.

  1. Declaration and initialization using Collections.addAll():

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

Collections.addAll(numbers, 1, 2, 3, 4, 5);

Here, we first declare an empty `ArrayList` of type `Integer`, and then use the `Collections.addAll()` method to add elements to the list in a convenient way.

Methods Of ArrayList In Java

Methods offered by the ArrayList class are:

MethodDescription
public boolean add(E element)Appends the specified element to the end of the list.
public void add(int index, E element)Inserts the specified element at the specified index.
public boolean addAll(Collection<? extends E> c)Appends all the elements in the specified collection to the end of the list.
public boolean addAll(int index, Collection<? extends E> c)Inserts all the elements in the specified collection into the list, starting from the specified index.
public void clear()Removes all elements from the list.
public Object clone()Returns a shallow copy of the ArrayList instance.
public boolean contains(Object o)Returns true if the list contains the specified element.
public E get(int index)Returns the element at the specified index in the list.
public int indexOf(Object o)Returns the index of the first occurrence of the specified element in the list, or -1 if not found.
public boolean isEmpty()Returns true if the list is empty.
public Iterator<E> iterator()Returns an iterator over the elements in the list.
public int lastIndexOf(Object o)Returns the index of the last occurrence of the specified element in the list, or -1 if not found.
public ListIterator<E> listIterator()Returns a list iterator over the elements in the list.
public E remove(int index)Removes the element at the specified index from the list.
public boolean remove(Object o)Removes the first occurrence of the specified element from the list.
public E set(int index, E element)Replaces the element at the specified index with the specified element.
public int size()Returns the number of elements in the list.
public List<E> subList(int fromIndex, int toIndex)Returns a view of the portion of the list between the specified indexes.
public Object[] toArray()Returns an array containing all the elements in the list.
public <T> T[] toArray(T[] a)Returns an array containing all the elements in the list, using the runtime type of the specified array.

Example

import java.util.ArrayList;

import java.util.Iterator;

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList

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

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Orange");

        fruits.add("Mango");

        // Get the size of the ArrayList

        System.out.println("Size of the ArrayList: " + fruits.size());

        // Check if the ArrayList is empty

        System.out.println("Is the ArrayList empty? " + fruits.isEmpty());

        // Access elements by index

        System.out.println("First element: " + fruits.get(0));

        System.out.println("Last element: " + fruits.get(fruits.size() - 1));

        // Iterate over the ArrayList using an Iterator

        System.out.println("Elements in the ArrayList:");

        Iterator<String> iterator = fruits.iterator();

        while (iterator.hasNext()) {

            System.out.println(iterator.next());

        }

        // Update an element at a specific index

        fruits.set(1, "Grapes");

        System.out.println("Updated ArrayList: " + fruits);

        // Remove an element by index

        fruits.remove(2);

        System.out.println("ArrayList after removal: " + fruits);

        // Remove an element by value

        boolean removed = fruits.remove("Mango");

        System.out.println("Was Mango removed? " + removed);

        // Check if the ArrayList contains an element

        System.out.println("Does the ArrayList contain 'Apple'? " + fruits.contains("Apple"));

        // Convert the ArrayList to an array

        String[] fruitsArray = fruits.toArray(new String[0]);

        System.out.print("ArrayList converted to array: ");

        for (String fruit: fruitsArray) {

            System.out.print(fruit + " ");

        }

        System.out.println();

    }

}

Output

Size of the ArrayList: 4

Is the ArrayList empty? false

First element: Apple

Last element: Mango

Elements in the ArrayList:

Apple

Banana

Orange

Mango

Updated ArrayList: [Apple, Grapes, Orange, Mango]

ArrayList after removal: [Apple, Grapes, Mango]

Was Mango removed? true

Does the ArrayList contain 'Apple'? true

ArrayList converted to array: Apple Grapes Mango

LinkedList In Java

LinkedList is a class in the Java Collections Framework that implements the List interface. It is an implementation of a doubly-linked list, where each element in the list is represented by a node that contains a reference to both the previous and the next node.

LinkedList provides efficient insertion and deletion operations at both ends of the list. However, it has slower access times compared to ArrayList, as accessing elements by index requires traversing the list from the beginning or end.

Key Features of LinkedList in Java

  • Dynamic Size: LinkedList can grow or shrink dynamically based on the elements added or removed.
  • Doubly-Linked: Each node in the LinkedList contains references to both the previous and the next node, allowing for efficient traversal in both directions.
  • No Random Access: Unlike ArrayList, LinkedList does not provide direct access to elements by index. To access an element, the list must be traversed from the beginning or end.
  • Efficient Insertion and Deletion: LinkedList excels at inserting or deleting elements at the beginning or end of the list, as it requires updating just a few references.

How to create LinkedList in Java

To create a LinkedList in Java, you can use the following constructors:

  1. LinkedList():

This constructor creates an empty LinkedList with no initial elements.

LinkedList<String> linkedList = new LinkedList<>();

In this example, we simply create an empty LinkedList called linkedList using the LinkedList constructor without any arguments.

  1. LinkedList(Collection<? extends E> c):

This constructor creates a LinkedList and initializes it with the elements from the specified collection c.

List<String> originalList = new ArrayList<>();

originalList.add(“Apple”);

originalList.add(“Banana”);

originalList.add(“Orange”);

LinkedList<String> linkedList = new LinkedList<>(originalList);

In this example, we first create an ArrayList called originalList and add elements to it. Then, we initialize a LinkedList called linkedList by passing originalList as an argument to the LinkedList constructor. This initializes the LinkedList with the elements from the original list.

Methods Of LinkedList In Java 

Methods offered by the LinkedList class are:

MethodDescription
boolean add(E element)Adds the specified element to the end of the list.
void add(int index, E element)Inserts the specified element at the specified position in the list.
boolean addAll(Collection<? extends E> c)Adds all the elements from the specified collection to the end of the list.
boolean addAll(int index, Collection<? extends E> c)Inserts all the elements from the specified collection into the list, starting at the specified position.
void clear()Removes all the elements from the list.
boolean contains(Object o)Returns true if the list contains the specified element, otherwise returns false.
E get(int index)Returns the element at the specified position in the list.
int indexOf(Object o)Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
int lastIndexOf(Object o)Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.
public E remove(int index)Removes the element at the specified position in the list and returns the removed element.
boolean remove(Object o)Removes the first occurrence of the specified element from the list. Returns true if the element was found and removed, otherwise returns false.
E set(int index, E element)Replaces the element at the specified position in the list with the specified element and returns the original element.
int size()Returns the number of elements in the list.
boolean isEmpty()Returns true if the list is empty, otherwise returns false.
Iterator<E> iterator()Returns an iterator over the elements in the list.
ListIterator<E> listIterator()Returns a list iterator over the elements in the list.
ListIterator<E> listIterator(int index)Returns a list iterator over the elements in the list, starting at the specified position.
E peek()Retrieves, but does not remove, the first element of the list. Returns null if the list is empty.
E poll()Retrieves and removes the first element of the list. Returns null if the list is empty.
E pop()Removes and returns the first element of the list.
void push(E element)Inserts the specified element at the beginning of the list.
void addFirst(E e)It is used to insert the given element at the beginning of a list.
void addLast(E e)It is used to append the given element to the end of a list.
E getFirst()It is used to return the first element in a list.
E getLast()It is used to return the last element in a list.
boolean offer(E e)It adds the specified element as the last element of a list.
boolean offerFirst(E e)It inserts the specified element at the front of a list.
boolean offerLast(E e)It inserts the specified element at the end of a list.
E peekFirst()It retrieves the first element of a list or returns null if a list is empty.
E peekLast()It retrieves the last element of a list or returns null if a list is empty.
E pollFirst()It retrieves and removes the first element of a list, or returns null if a list is empty.
E pollLast()It retrieves and removes the last element of a list, or returns null if a list is empty.

Example

import java.util.LinkedList;

public class LinkedListExample {

    public static void main(String[] args) {

        // Create a LinkedList

        LinkedList<String> linkedList = new LinkedList<>();

        // Add elements to the LinkedList

        linkedList.add("Apple");

        linkedList.add("Banana");

        linkedList.add("Orange");

        linkedList.add("Mango");

        // Display the LinkedList

        System.out.println("LinkedList: " + linkedList);

        // Get the size of the LinkedList

        int size = linkedList.size();

        System.out.println("Size of LinkedList: " + size);

        // Check if the LinkedList is empty

        boolean isEmpty = linkedList.isEmpty();

        System.out.println("Is LinkedList empty? " + isEmpty);

        // Get the first element of the LinkedList

        String firstElement = linkedList.getFirst();

        System.out.println("First Element: " + firstElement);

        // Get the last element of the LinkedList

        String lastElement = linkedList.getLast();

        System.out.println("Last Element: " + lastElement);

        // Remove an element from the LinkedList

        boolean isRemoved = linkedList.remove("Banana");

        System.out.println("Is Banana removed? " + isRemoved);

        System.out.println("Updated LinkedList: " + linkedList);

        // Replace an element in the LinkedList

        linkedList.set(1, "Grapes");

        System.out.println("Updated LinkedList: " + linkedList);

        // Check if the LinkedList contains an element

        boolean contains = linkedList.contains("Mango");

        System.out.println("Does LinkedList contain Mango? " + contains);

        // Iterate over the LinkedList using for-each loop

        System.out.println("Iterating over LinkedList:");

        for (String element: linkedList) {

            System.out.println(element);

        }

    }

}

Output

LinkedList: [Apple, Banana, Orange, Mango]

Size of LinkedList: 4

Is LinkedList empty? false

First Element: Apple

Last Element: Mango

Is Banana removed? true

Updated LinkedList: [Apple, Orange, Mango]

Updated LinkedList: [Apple, Grapes, Mango]

Does LinkedList contain Mango? true

Iterating over LinkedList:

Apple

Grapes

Mango

ArrayList VS LinkedList In Java 

AspectArrayListLinkedList
Data StructureDynamic arrayDoubly-linked list
Random AccessEfficient (O(1))Inefficient (O(n))
InsertionSlower (O(n))Faster (O(1))
DeletionSlower (O(n))Faster (O(1))
Memory OverheadLowerHigher
IterationFaster (as elements are stored in contiguous memory)Slower (as elements are scattered in memory)
UsageBest suited for random access and retrievalBest suited for frequent insertions/removals

Vector In Java

Vector is a class in Java that represents a dynamic array, similar to ArrayList. It is a part of the Java Collections Framework and provides several features and functionalities for manipulating and storing elements.

Key features of Vector: 

  • Dynamic Size: Vector can grow or shrink dynamically based on the number of elements.
  • Indexed Access: Elements in a Vector can be accessed using their index.
  • Ordered Elements: Vector maintains the order of elements as they are added.
  • Duplicate Elements: Vector allows duplicate elements.
  • Thread-Safe: Vector is synchronized and can be safely used in multi-threaded environments.

How to create a Vector in Java 

Creating a Vector in Java involves initializing an instance of the Vector class with appropriate parameters. In this topic, we will explore the different ways to create a Vector in Java and understand the constructors available for creating Vectors.

  1. Using the Default Constructor:
    Vector<E> vector = new Vector<E>();

    The default constructor creates an `empty vector` with the default initial capacity (`10`). The type parameter `<E>` specifies the type of elements that the Vector will hold.
  1. Specifying Initial Capacity:
    Vector<E> vector = new Vector<E>(int initialCapacity);

    The constructor with the int `initialCapacity` parameter creates a vector with the specified initial `capacity`. The initial capacity defines the number of elements the `vector` can hold before it needs to resize.
  1. Specifying Initial Capacity and Capacity Increment:
    Vector<E> vector = new Vector<E>(int initialCapacity, int capacityIncrement);

    This constructor creates a Vector with the specified initial capacity and capacity increment. The capacity increment determines the amount by which the Vector’s capacity will increase if it needs to be resized.
  1. Creating Vector from a Collection:
    Vector<E> vector = new Vector<E>(Collection<? extends E> c);

    This constructor creates a Vector and initializes it with the elements from the specified collection c. The elements are added to the Vector in the order they appear in the collection.

Methods Of Vector In Java

MethodDescription
void addElement(E obj)Adds the specified element to the end of the Vector.
void removeElement(Object obj)Removes the first occurrence of the specified element from the Vector.
boolean contains(Object obj)Checks if the Vector contains the specified element.
E elementAt(int index)Returns the element at the specified index in the Vector.
int indexOf(Object obj)Returns the index of the first occurrence of the specified element in the Vector, or -1 if the element is not found.
boolean isEmpty()Checks if the Vector is empty.
int size()Returns the number of elements in the Vector.
void clear()Removes all elements from the Vector.
E get(int index)Returns the element at the specified index in the Vector.
void set(int index, E element)Replaces the element at the specified index in the Vector with the specified element.
boolean removeElementAt(int index)Removes the element at the specified index from the Vector.
void insertElementAt(E obj, int index)Inserts the specified element at the specified index in the Vector.
void removeAllElements()Removes all elements from the Vector.
Enumeration<E> elements()Returns an enumeration of the elements in the Vector.
void trimToSize()Trims the capacity of the Vector to be the same as its size.
void setSize(int newSize)Sets the size of the Vector to the specified newSize. If the newSize is greater than the current size, null elements are added to the end of the Vector. If the newSize is less than the current size, elements at the end are truncated.
void sort(Comparator<? super E> c)Sorts the elements of the Vector using the specified Comparator.
void add()It is used to append the specified element in the given vector.
void addAll()It is used to append all of the elements in the specified collection to the end of this Vector.
int capacity()It is used to get the current capacity of this vector.
clone()It returns a clone of this vector.

Example

import java.util.Vector;

public class VectorExample {

    public static void main(String[] args) {

        // Create a new Vector

        Vector<String> vector = new Vector<>();

        // Add elements to the Vector

        vector.addElement("Apple");

        vector.addElement("Banana");

        vector.addElement("Orange");

        // Get the size of the Vector

        int size = vector.size();

        System.out.println("Size of the Vector: " + size);

        // Check if the Vector is empty

        boolean isEmpty = vector.isEmpty();

        System.out.println("Is the Vector empty? " + isEmpty);

        // Access elements by index

        String firstElement = vector.elementAt(0);

        System.out.println("First element: " + firstElement);

        // Update an element at a specific index

        vector.set(1, "Mango");

        System.out.println("Updated Vector: " + vector);

        // Remove an element by value

        vector.removeElement("Apple");

        System.out.println("Vector after removing 'Apple': " + vector);

        // Iterate over the elements using Enumeration

        System.out.println("Iterating over the elements:");

        Enumeration<String> enumeration = vector.elements();

        while (enumeration.hasMoreElements()) {

            String element = enumeration.nextElement();

            System.out.println(element);

        }

        // Remove all elements from the Vector

        vector.removeAllElements();

        System.out.println("Vector after removing all elements: " + vector);

    }

}

Output

Size of the Vector: 3

Is the Vector empty? false

First element: Apple

Updated Vector: [Apple, Mango, Orange]

Vector after removing 'Apple': [Mango, Orange]

Iterating over the elements:

Mango

Orange

Vector after removing all elements: []

ArrayList VS Vector In Java

AspectArrayListVector
Thread-safeNot synchronizedSynchronized
PerformanceFasterSlower
GrowthIncreases capacity by 50%Doubles the capacity
LegacyIntroduced in Java 1.2Introduced in Java 1.0
IteratorFail-fastFail-safe
Data retrievalEfficient with get and set operationsEfficient with get and set operations
UsagePreferred for single-threaded environmentsSuitable for multi-threaded environments

Stack Class In Java  

The Stack class in Java is a subclass of the Vector class and represents a last-in-first-out (LIFO) data structure. It follows the principle of “last in, first out” where the element that is inserted last is the first one to be removed. The Stack class provides methods for pushing elements onto the stack, popping elements from the stack, and accessing the top element without removing it.

Key Features of Stack Class

Extends Vector: The Stack class in Java extends the Vector class and inherits its methods, making it a synchronized and thread-safe implementation of a stack.

LIFO Order: The elements in a Stack are stored and accessed based on the Last-In-First-Out (LIFO) order, where the most recently added element is at the top of the stack.

Dynamic Size: The Stack class automatically adjusts its size as elements are added or removed, allowing for dynamic storage of data.

How to create a Stack in Java  

To create a stack in Java, you can utilize the Stack class provided by the Java Collections framework. The Stack class is part of the `java.util package`, so you need to import it before using it in your code. Here’s a general syntax to create a stack in Java:

import java.util.Stack;

// Create a stack

Stack<DataType> stack = new Stack<>();

In the above code snippet:

`DataType` represents the type of elements you want to store in the stack. Replace it with the actual data type you intend to use, such as Integer, String, or any custom class.

`stack` is the name of the stack object you are creating. You can choose any valid variable name according to your preference.

Methods Of Stack In Java

MethodDescription
push(E element)This method pushes the specified element onto the top of the stack. It modifies the stack by adding the element at the top.
pop()This method removes and returns the element at the top of the stack. It modifies the stack by removing the top element.
peek()This method returns the element at the top of the stack without removing it. It allows you to access the top element without modifying the stack.
empty()This method checks if the stack is empty. It returns true if the stack is empty, and false otherwise.
size()This method returns the number of elements present in the stack. It gives you the current size of the stack.
search(Object element)This method searches for the specified element in the stack. It returns the 1-based position of the element in the stack if found, and -1 if the element is not present.

Example

import java.util.Stack;

public class StackExample {

    public static void main(String[] args) {

        // Create a new stack

        Stack<String> stack = new Stack<>();

        // Push elements onto the stack

        stack.push("Apple");

        stack.push("Banana");

        stack.push("Cherry");

        // Print the stack

        System.out.println("Stack: " + stack);

        // Pop an element from the stack

        String poppedElement = stack.pop();

        System.out.println("Popped Element: " + poppedElement);

        System.out.println("Stack after pop: " + stack);

        // Peek the top element in the stack

        String topElement = stack.peek();

        System.out.println("Top Element: " + topElement);

        System.out.println("Stack after peek: " + stack);

        // Check if the stack is empty

        boolean isEmpty = stack.empty();

        System.out.println("Is stack empty? " + isEmpty);

        // Get the size of the stack

        int size = stack.size();

        System.out.println("Size of stack: " + size);

        // Search for an element in the stack

        int index = stack.search("Banana");

        System.out.println("Index of 'Banana': " + index);

    }

}

Output:

Stack: [Apple, Banana, Cherry]

Popped Element: Cherry

Stack after pop: [Apple, Banana]

Top Element: Banana

Stack after peek: [Apple, Banana]

Is stack empty? false

Size of stack: 2

Index of 'Banana': 1

Conclusion 

  • The List interface in Java represents an ordered collection of elements that allows duplicates.
  • Lists can be declared using the List interface, and they are typically instantiated using concrete classes like ArrayList, LinkedList, or Vector.
  • The List interface is the root of the list hierarchy, with ArrayList, LinkedList, and Vector implementing it.
  • The List interface provides various methods for manipulating and accessing elements in a list, such as adding, removing, retrieving, and modifying elements.
  • ArrayList, LinkedList, and Vector are the classes that inherit from the List interface, providing different implementations of list functionality.
  • ArrayList is an implementation of the List interface backed by an array, providing dynamic resizing and fast random access to elements.
  • ArrayList can be declared and initialized using the ArrayList class constructor or by assigning an existing ArrayList to a new variable.
  • ArrayList provides methods for adding, removing, accessing, and manipulating elements, as well as utility methods for searching, sorting, and checking for containment.
  • LinkedList is an implementation of the List interface that uses a doubly-linked list structure, offering efficient insertion and removal at both ends of the list.
  • LinkedList can be declared and initialized using the LinkedList class constructor or by assigning an existing LinkedList to a new variable.
  • LinkedList provides methods for adding, removing, accessing, and manipulating elements, including operations specific to linked lists such as adding/removing elements at the beginning or end.
  • Vector is a synchronized implementation of the List interface, providing thread-safe operations but with lower performance compared to ArrayList or LinkedList.
  • Vector can be created using various constructors, allowing for capacity control and initializing from an existing collection.
  • Vector offers methods for adding, removing, accessing, and manipulating elements, including synchronized versions of the List interface methods.
  • Stack is a subclass of Vector that represents a Last-In-First-Out (LIFO) data structure, where elements are added and removed from the top of the stack.

Happy Listing!!

Leave a Reply

Your email address will not be published. Required fields are marked *