Key differences between List and ArrayList in Java

List in Java

In Java, a List is an interface in the java.util package that represents an ordered collection of elements. It allows for duplicate entries and provides control over where in the list each element is inserted. Users can access elements by their integer index (position in the list), search for elements, and iterate over the list. The List interface extends the Collection interface and is implemented by several classes, including ArrayList, LinkedList, and Vector. Each offers different performance characteristics. For example, ArrayList provides O(1) time complexity for random access but O(n) for adding or removing elements at the start or middle. LinkedList, however, offers better performance for such modifications due to its node-based structure. The choice of implementation depends on specific requirements regarding performance and type of operations needed.

Functions of List in Java:

  • add(E e):

Adds the specified element to the end of the list.

  • add(int index, E element):

Inserts the specified element at the specified position in the list.

  • addAll(Collection<? extends E> c):

Appends all of the elements in the specified collection to the end of the list.

  • addAll(int index, Collection<? extends E> c):

Inserts all the elements in the specified collection into the list, starting at the specified position.

  • clear():

Removes all of the elements from the list.

  • contains(Object o):

Returns true if the list contains the specified element.

  • containsAll(Collection<?> c):

Returns true if the list contains all the elements of the specified collection.

  • get(int index):

Returns the element at the specified position in the list.

  • indexOf(Object o):

Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.

  • isEmpty():

Returns true if the list contains no elements.

  • iterator():

Returns an iterator over the elements in the list in proper sequence.

  • lastIndexOf(Object o):

Returns the index of the last occurrence of the specified element in the list, or -1 if the list does not contain the element.

  • listIterator(), listIterator(int index):

Returns a list iterator over the elements in the list (in proper sequence), optionally starting from the specified position in the list.

  • remove(Object o):

Removes the first occurrence of the specified element from the list, if it is present.

  • remove(int index):

Removes the element at the specified position in the list.

  • removeAll(Collection<?> c):

Removes from the list all its elements that are contained in the specified collection.

  • retainAll(Collection<?> c):

Retains only the elements in the list that are contained in the specified collection.

  • set(int index, E element):

Replaces the element at the specified position in the list with the specified element.

  • size():

Returns the number of elements in the list.

  • subList(int fromIndex, int toIndex):

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

Example of List in Java:

In this example, I’ll use an ArrayList to demonstrate common operations like adding elements, retrieving elements, and iterating over the list.

import java.util.ArrayList;

import java.util.List;

public class ListExample {

    public static void main(String[] args) {

        // Creating a List

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

        // Adding elements to the List

        fruits.add(“Apple”);

        fruits.add(“Banana”);

        fruits.add(“Cherry”);

        fruits.add(“Date”);

        // Accessing elements from the List

        System.out.println(“First fruit: ” + fruits.get(0));  // Output: Apple

        // Removing an element from the List

        fruits.remove(“Date”);  // Removes “Date”

        fruits.add(2, “Elderberry”);  // Adds “Elderberry” at index 2

        // Size of the List

        System.out.println(“Total fruits: ” + fruits.size());  // Output: 4

        // Iterating over the List

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

        for (String fruit : fruits) {

            System.out.println(fruit);

        }

        // Checking if the List contains a specific element

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

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

        }

    }

}

Explanation of the Code:

  • Import and Creation:

ArrayList class is imported, and a List named fruits is instantiated as an ArrayList.

  • Adding Elements:

Elements are added to the list using the add() method. Elements can be added either at the end of the list or at a specific index.

  • Accessing Elements:

get() method is used to retrieve an element from a specified index.

  • Removing Elements:

remove() method can be used to remove an element either by object name or index. Another element is added at a specific position with add(index, element).

  • Size:

size() method returns the number of elements in the list.

  • Iteration:

The enhanced for loop (for-each loop) is used to iterate over the list and print each fruit.

  • Containment Check:

contains() method checks if a specific item is present in the list.

ArrayList in Java

In Java, an ArrayList is a resizable array implementation of the List interface, part of the java.util package. It provides a dynamic array that can grow as needed, unlike standard arrays which have a fixed length. ArrayList is backed by an array of objects; when the capacity is exceeded, it automatically increases in size by reallocating a new array. This feature makes ArrayList highly flexible for scenarios where the number of elements is not known upfront. Access to any element by its index position is efficient (O(1) time complexity), making ArrayList a preferred choice for lists where frequent read operations and less frequent additions or deletions occur. However, the performance can be impacted during resizing and when inserting or removing elements at positions other than the end.

Functions of ArrayList in Java:

  • add(E element):

Adds the specified element to the end of the list. This method ensures that the ArrayList can accommodate the new element by automatically increasing its capacity if necessary.

  • add(int index, E element):

Inserts the specified element at the specified position in the list, shifting the element currently at that position (if any) and any subsequent elements to the right.

  • remove(int index):

Removes the element at the specified position in the list. All subsequent elements are shifted to the left (subtracts one from their indices).

  • remove(Object o):

Removes the first occurrence of the specified element from the list, if it is present. If the list contains one or more such elements, it removes the first occurrence.

  • get(int index):

Returns the element at the specified position in the list.

  • set(int index, E element):

Replaces the element at the specified position in the list with the specified element.

  • size():

Returns the number of elements in the list. This method is commonly used in loops and when making checks on the size of the list.

  • clear():

Removes all of the elements from the list. The list will be empty after this call returns.

Example of ArrayList in Java:

Here’s an example demonstrating the use of an ArrayList in Java, illustrating several of the functions mentioned, such as adding, removing, and accessing elements. This example includes comments to help explain each part of the code:

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        // Creating an ArrayList of String type

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

        // Adding elements to the ArrayList

        books.add(“To Kill a Mockingbird”);

        books.add(“1984”);

        books.add(“The Great Gatsby”);

        // Displaying the initial list of books

        System.out.println(“Initial list: ” + books);

        // Adding an element at a specific position

        books.add(1, “Brave New World”);

        // Accessing elements from the ArrayList

        System.out.println(“Book at index 2: ” + books.get(2));

        // Replacing an element

        books.set(0, “Pride and Prejudice”);

        // Removing an element by index

        books.remove(2);

        // Removing an element by object

        books.remove(“1984”);

        // Getting the size of the ArrayList

        System.out.println(“Number of books: ” + books.size());

        // Displaying the modified list of books

        System.out.println(“Updated list: ” + books);

        // Clearing all elements

        books.clear();

        System.out.println(“List after clear: ” + books);

    }

}

Explanation of the Code:

  • Initialization:

An ArrayList named books is created to store strings.

  • Adding Elements:

Books are added to the list using add(String element). A book is also inserted at a specific position using add(int index, String element).

  • Accessing an Element:

get(int index) method retrieves the book at index 2.

  • Modifying Elements:

set(int index, String element) is used to replace the book at index 0.

  • Removing Elements:

Books are removed both by their position using remove(int index) and by their content using remove(Object o).

  • Size and Clearing:

size() method is called to check how many books are currently in the list. The clear() method is used to remove all elements from the ArrayList.

Key differences between List and ArrayList in Java

Aspect List ArrayList
Type Interface Class
Implementation No direct implementation Direct implementation
Methods Abstract methods Concrete methods
Storage Requirement Not applicable Requires memory allocation
Instantiation Cannot be instantiated Can be instantiated
Flexibility Requires implementation Ready to use
Usability General contract Specific functionality
Specific Methods None Size, trimToSize, etc.
Performance Depends on implementation Generally fast access
Resizability Implementation dependent Automatically resizable
Inheritance Can be implemented by many classes Inherits from AbstractList
Direct Data Manipulation No direct access Direct access via indexes
Multiple Implementations Yes No (single implementation)
Use Case For declaring structure For practical use
Subtyping Flexibility High (more abstract) Lower (more concrete)

Key Similarities between List and ArrayList in Java

  • Collection Framework:

Both List and ArrayList are part of the Java Collections Framework, which provides a standardized architecture to manage and manipulate groups of objects.

  • Ordered Elements:

Both maintain elements in a specific insertion order, making it easy to iterate over the elements in the order they were added.

  • Element Access:

Both allow positional access to elements, meaning you can retrieve elements based on their numerical position in the list.

  • Support for Generics:

Both List and ArrayList support generics, allowing them to be parameterized with a specific type, enhancing type safety and reducing the need for type casting.

  • Dynamic Operations:

Both support dynamic operations such as insertion, deletion, and traversal of elements.

  • Interface and Implementation:

ArrayList class implements the List interface, meaning it adheres to the contract defined by the List interface. This makes ArrayList a direct practical implementation of the List‘s abstract behaviors.

  • Iterators:

Both provide access to Iterator and ListIterator, which allow forward and backward traversal of the list along with modifications such as adding, replacing, and removing elements during iteration.

  • Method Set:

The basic methods in ArrayList (such as add, remove, get, set, and others) are all defined in the List interface, ensuring consistency across all concrete implementations of List.

error: Content is protected !!